<?php
/**
 * @version $Id: wrd.php 155 2011-11-07 09:06:19Z truongnhan0311@gmail.com $
 */
// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.helper');

class WrdHelper
{
	public static function addSubmenu($submenu = 'wrd',$submenu_level1 = '')
	{
		$submenu = strtolower($submenu);
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_MENU_DASHBOARD'), 'index.php?option=com_wrd', $submenu == 'dashboard');
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_MENU_CONFIG'), 'index.php?option=com_wrd&controller=config', $submenu == 'config');
		
		if($submenu == 'config'){
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_COUNTRY'), 'index.php?option=com_wrd&controller=country', $submenu_level1 == 'country');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_CITY'), 'index.php?option=com_wrd&controller=city', $submenu_level1 == 'city');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_DISTRIC'), 'index.php?option=com_wrd&controller=distric', $submenu_level1 == 'distric');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_EDUCATION'), 'index.php?option=com_wrd&controller=education', $submenu_level1 == 'education');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_DEPARTMENT'), 'index.php?option=com_wrd&controller=department', $submenu_level1 == 'department');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_INDUSTRY'), 'index.php?option=com_wrd&controller=industry', $submenu_level1 == 'industry');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_JOB'), 'index.php?option=com_wrd&controller=job', $submenu_level1 == 'job');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_HOBBIES'), 'index.php?option=com_wrd&controller=hobbies', $submenu_level1 == 'hobbies');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_STATUS'), 'index.php?option=com_wrd&controller=status', $submenu_level1 == 'status');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_OCLUB'), 'index.php?option=com_wrd&controller=oclub', $submenu_level1 == 'oclub');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_CEMAIL'), 'index.php?option=com_wrd&controller=cemail', $submenu_level1 == 'cemail');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_BATION'), 'index.php?option=com_wrd&controller=bation', $submenu_level1 == 'bation');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_REGFIELDS'), 'index.php?option=com_wrd&controller=regfield', $submenu_level1 == 'regfield');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_AWEEKEND'), 'index.php?option=com_wrd&controller=aweekend', $submenu_level1 == 'aweekend');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_LPREFER'), 'index.php?option=com_wrd&controller=lprefer', $submenu_level1 == 'lprefer');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_LNUM'), 'index.php?option=com_wrd&controller=lnum', $submenu_level1 == 'lnum');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_COMPANYNAME'), 'index.php?option=com_wrd&controller=companyname', $submenu_level1 == 'companyname');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_PCATEGORY'), 'index.php?option=com_wrd&controller=pcategory', $submenu_level1 == 'pcategory');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_PRODUCTS'), 'index.php?option=com_wrd&controller=products', $submenu_level1 == 'products');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_CPOINT'), 'index.php?option=com_wrd&controller=cpoint', $submenu_level1 == 'cpoint');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_PROJECTS'), 'index.php?option=com_wrd&controller=projects', $submenu_level1 == 'projects');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_CLUBS'), 'index.php?option=com_wrd&controller=clubs', $submenu_level1 == 'clubs');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_OUTLETS'), 'index.php?option=com_wrd&controller=outlets', $submenu_level1 == 'outlets');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_SOURCES'), 'index.php?option=com_wrd&controller=sources', $submenu_level1 == 'sources');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_CONFIG_GLCONFIGS'), 'index.php?option=com_glconfigs', $submenu_level1 == 'glconfigs');
		}
		
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_MENU_PROFILE'), 'index.php?option=com_wrd&controller=profile', $submenu == 'profile');
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_MENU_POINT_POLICY'), 'index.php?option=com_wrd&controller=cpoint', $submenu == 'cpoint');
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_MENU_COMPLAIN'), 'index.php?option=com_wrd&controller=complain', $submenu == 'complain');
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_MENU_REPORT'), 'index.php?option=com_wrd&controller=reports', $submenu == 'reports');
		
		if($submenu == 'reports'){
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_MEMBERSHIP'), 'index.php?option=com_wrd&controller=reports&layout=generalreport', $submenu_level1 == 'generalreport');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_OUTLETREVENUE'), 'index.php?option=com_wrd&controller=reports&layout=memberpendingreportsum', $submenu_level1 == 'memberpendingreportsum');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_TRANSACTION'), 'index.php?option=com_wrd&controller=reports&layout=transactionreport', $submenu_level1 == 'transactionreport');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_MEMBERBIRTHDAY'), 'index.php?option=com_wrd&controller=reports&layout=memberbirthday', $submenu_level1 == 'memberbirthday');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_SUMMARYMEMBERSPNEDING'), 'index.php?option=com_wrd&controller=reports&layout=outletreport', $submenu_level1 == 'outletreport');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_WINDSORVIPMEMBERSHIPCLUB'), 'index.php?option=com_wrd&controller=reports&layout=memberstatistic', $submenu_level1 == 'memberstatistic');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_MEMBERSTATISTICONJOB'), 'index.php?option=com_wrd&controller=reports&layout=memberstatisticjob', $submenu_level1 == 'memberstatisticjob');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_MASTERLISTREPORT'), 'index.php?option=com_wrd&controller=reports&layout=memberreport', $submenu_level1 == 'memberreport');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_COMPLAINREPORT'), 'index.php?option=com_wrd&controller=reports&layout=complainreport', $submenu_level1 == 'complainreport');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_MEMBERSERVICES'), 'index.php?option=com_wrd&controller=reports&layout=memberservicereport', $submenu_level1 == 'memberservicereport');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_REDEMPTIONREPORT'), 'index.php?option=com_wrd&controller=reports&layout=redemptionreport', $submenu_level1 == 'redemptionreport');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_REDEMPTIONREPORTPRODUCT'), 'index.php?option=com_wrd&controller=reports&layout=redemptionreportproduct', $submenu_level1 == 'redemptionreportproduct');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_REDEMPTIONREPORTVOUCHER'), 'index.php?option=com_wrd&controller=reports&layout=redemptionreportvoucher', $submenu_level1 == 'redemptionreportvoucher');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_APPROVEVOUCHER'), 'index.php?option=com_wrd&controller=reports&layout=approvevoucher', $submenu_level1 == 'approvevoucher');
			JHtmlSidebar::addEntry('&nbsp;&nbsp;|_'.JText::_('COM_WRD_ADMIN_MENU_REDEMREPORTVOUCHERPRODUCT'), 'index.php?option=com_wrd&controller=reports&layout=redempreport', $submenu_level1 == 'redempreport');
		}
		
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_DISCOUNT_POLICY'), 'index.php?option=com_wrd&controller=discount', $submenu == 'discount');
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_DISCOUNT_POLICY_OFFLINE'), 'index.php?option=com_wrd&controller=discountoff', $submenu == 'discountoff');
		JHtmlSidebar::addEntry(JText::_('COM_WRD_ADMIN_DISCOUNT_MEMBER_SERVICES'), 'index.php?option=com_wrd&controller=mservices', $submenu == 'mservices');
		
	}
	
	
	public function getListPCategory($order_field = "title", $sort="ASC", $limit="4"){
		$db = &JFactory::getDbo();
		$query = "SELECT * FROM #__wrd_pcategory order by ".$order_field." ".$sort." limit 0,".$limit;
		$db->setQuery($query);
		return $db->loadObjectList();
	}
	
	public function sendEmailPointNotice($post){
		$user = &JFactory::getUser();
		
		$mapping_key = array();
		$mapping_key['title'] 				= 'Title';
		$mapping_key['p_code'] 				= 'Projects';
		$mapping_key['c_code'] 				= 'Clubs';
		$mapping_key['o_code'] 				= 'Outlets';
		$mapping_key['published_up'] 		= 'Publish up';
		$mapping_key['published_down'] 		= 'Publish down';
		$mapping_key['date'] 				= 'Date';
		$mapping_key['point'] 				= 'Points';
		$mapping_key['gender'] 				= 'Gender';
		$mapping_key['time'] 				= 'Time';
		$mapping_key['type'] 				= 'Type';
		$mapping_key['published'] 			= 'Publish';
		
		$mapping_key_lev1['time']['m'] 			= 'Morning';
		$mapping_key_lev1['time']['f_m_hour'] 	= 'From Hour';
		$mapping_key_lev1['time']['t_m_hour'] 	= 'To Hour';
		
		$mapping_key_lev1['time']['a'] 			= 'Afternoon';
		//$mapping_key_lev1['time']['f_a_hour'] 	= 'From Hour';
		//$mapping_key_lev1['time']['t_a_hour'] 	= 'To Hour';
		
		$mapping_key_lev1['time']['e'] 			= 'Evening';
		//$mapping_key_lev1['time']['f_e_hour'] 	= 'From Hour';
		//$mapping_key_lev1['time']['t_e_hour'] 	= 'To Hour';
		
		$mapping_key_lev1['type']['f'] 			= 'Food';
		$mapping_key_lev1['type']['b'] 			= 'Beverage';
		$mapping_key_lev1['type']['o'] 			= 'Other';
		
		$mapping_key_lev1['date']['mon_r'] 		= 'Monday';
		$mapping_key_lev1['date']['tue_r'] 		= 'Tueday';
		$mapping_key_lev1['date']['wed_r'] 		= 'Wednesday';
		$mapping_key_lev1['date']['thu_r'] 		= 'Thursday';
		$mapping_key_lev1['date']['fri_r'] 		= 'Friday';
		$mapping_key_lev1['date']['sat_r'] 		= 'Saturday';
		$mapping_key_lev1['date']['sun_r'] 		= 'Sunday';

		$old_item = $user->currentpoint;
		
		//print_r($old_item);
		$emailSubject =  'WMCVIP - A point policy has been created or modified - System report';
		
		$email	= array('dinh.chau@wmcvietnam.com','truongnhan0311@gmail.com' );
		$mailFrom = 'WMCVIP';
		
		$emailBody = '<p><b>User Name:</b>'.$user->name.'</p>';
		$emailBody .= '<p><b>User ID:</b>'.$user->id.'</p>';
		$emailBody .= '<p><b>User Email:</b>'.$user->email.'</p>';
		
		$emailBody .= '<table width="100%">';
		$emailBody .= '<table><tr><td></td><td width="35%"><b>OLD VALUE</b></td><td width="35%"><b>NEW VALUE</b></td></tr>';
		foreach ($mapping_key as $key => $value) {
			$emailBody .=	'<tr>';
			if($key == 'ordinary' || $key == 'multiples'){
				
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.$old_item->$key.'</td>';
				$emailBody .= 	'<td>'.intval($post[$key]).'</td>';
			}
			elseif( $key == 'p_code'){
				
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.self::getProjectName($old_item->$key).'</td>';
				$emailBody .= 	'<td>'.self::getProjectName($post[$key]).'</td>';
			}
				
			elseif( $key == 'c_code'){
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.self::getClubName($old_item->$key).'</td>';
				$emailBody .= 	'<td>'.self::getClubName($post[$key]).'</td>';
			}
			else if($key == 'o_code'){
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.self::getOutletNameList($old_item->$key).'</td>';
				$emailBody .= 	'<td>'.self::getOutletNameList($post[$key]).'</td>';
			}
			else if($key == 'date'){
				$date_old = array();
				$date_new = array();
				foreach ($mapping_key_lev1[$key] as $key_lev1 => $row_lev1){
					if($old_item->$key_lev1 == 1)
						$date_old[] = $row_lev1;
					
					if($post[$key_lev1] == 1)
						$date_new[] = $row_lev1;
				}

				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.implode(',', $date_old).'</td>';
				$emailBody .= 	'<td>'.implode(',', $date_new).'</td>';
			}
			elseif($key == 'type'){
				$date_old = array();
				$date_new = array();
				foreach ($mapping_key_lev1[$key] as $key_lev1 => $row_lev1){
					if($old_item->$key_lev1 == 1)
						$date_old[] = $row_lev1;
						
					if($post[$key_lev1] == 1)
						$date_new[] = $row_lev1;
				}
				
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.implode(',', $date_old).'</td>';
				$emailBody .= 	'<td>'.implode(',', $date_new).'</td>';
			}
			elseif($key == 'time'){
				$date_old = '';
				$date_new = '';
				foreach ($mapping_key_lev1[$key] as $key_lev1 => $row_lev1){
					if($key_lev1 == 'm'){
						if($old_item->$key_lev1 == 1){
							$date_old .= $row_lev1.': ';
							$date_old .= 'from '.$old_item->f_m_hour.' hour ';
							$date_old .= 'to '.$old_item->t_m_hour.' hour<br>';
						}
						
						if($post[$key_lev1] == 1){
							$date_new .= $row_lev1.': ';
							$date_new .= 'from '.$post['f_m_hour'].' hour ';
							$date_new .= 'to '.$post['t_m_hour'].' hour<br>';
						}
					}
					elseif($key_lev1 == 'a'){
						if($old_item->$key_lev1 == 1){
							$date_old .= $row_lev1.': ';
							$date_old .= 'from '.$old_item->f_a_hour.' hour ';
							$date_old .= 'to '.$old_item->t_a_hour.' hour<br>';
						}
						
						if($post[$key_lev1] == 1){
							$date_new .= $row_lev1.': ';
							$date_new .= 'from '.$post['f_a_hour'].' hour ';
							$date_new .= 'to '.$post['t_a_hour'].' hour<br>';
						}
					}else{
						if($old_item->$key_lev1 == 1){
							$date_old .= $row_lev1.': ';
							$date_old .= 'from '.$old_item->f_e_hour.' hour ';
							$date_old .= 'to '.$old_item->t_e_hour.' hour<br>';
						}
						
						if($post[$key_lev1] == 1){
							$date_new .= $row_lev1.': ';
							$date_new .= 'from '.$post['f_e_hour'].' hour ';
							$date_new .= 'to '.$post['t_e_hour'].' hour<br>';
						}
					}
				}
			
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.$date_old.'</td>';
				$emailBody .= 	'<td>'.$date_new.'</td>';
			}
			else{
				$emailBody .=	'<tr>';
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.$old_item->$key.'</td>';
				$emailBody .= 	'<td>'.$post[$key].'</td>';
			}
				
			$emailBody .=	'</tr>';
		}
		
		$emailBody .= '<table>';
		
		return JUtility::sendMail($mailFrom, 'WMCVIP', $email, $emailSubject, $emailBody,1);
	}
	
	/*
	 * @Hung Phan :( 
	 */
	public function getOutletTranslate($code){
				
		$outlet = array();
		
		switch ($code){
			
			case 111 :
				
				$outlet['name']    =  JText::_('WRD_PROMOTION_AMIGO');
				$outlet['address'] =  JText::_('WRD_PROMOTION_AMIGO_ADDR'); break;
			
			case 131 :
				$outlet['name']    =  JText::_('WRD_PROMOTION_CCNH');
				$outlet['address'] =  JText::_('WRD_PROMOTION_CCNH_ADDR'); break;
				
			case 121 :
				$outlet['name']    =  JText::_('WRD_PROMOTION_DUCBAO');
				$outlet['address'] =  JText::_('WRD_PROMOTION_DUCBAO_ADDR'); break;
				
			case 181 :
				$outlet['name']    =  JText::_('WRD_PROMOTION_KISSHO');
				$outlet['address'] =  JText::_('WRD_PROMOTION_KISSHO_ADDR'); break;
			
			case 221 :
				$outlet['name']    =  JText::_('WRD_PROMOTION_CCAD');
				$outlet['address'] =  JText::_('WRD_PROMOTION_CCAD_ADDR'); break;
			
			case 211 :
				$outlet['name']    =  JText::_('WRD_PROMOTION_NGANDINH');
				$outlet['address'] =  JText::_('WRD_PROMOTION_NGANDINH_ADDR'); break;
			
			case 191 :
				$outlet['name']    =  JText::_('WRD_PROMOTION_TOTT');
				$outlet['address'] =  JText::_('WRD_PROMOTION_TOTT_ADDR'); break;
			
			case 22 :
				$outlet['name']    =  JText::_('WRD_PROMOTION_SPA');
				$outlet['address'] =  JText::_('WRD_PROMOTION_SPA_ADDR'); break;
			
			default:
				
				$outlet['name']    =  "";
				$outlet['address'] =  ""; break;
			
					
		}
		return $outlet;
		
		
	}
	/*
	 * Send Email when redemption
	* @Hung
	*/
	public function sendEmailWhenRedemption($user_profile,$list_items){

		$db = &JFactory::getDbo();
		//get email template
		$sql = 'select * from #__wrd_cemail where `action` = "redemption_notice"';
		$db->setQuery($sql) ;
		$email_template = $db->loadObject();
	
		if(!empty($email_template)){
		
			if($user_profile->nationality == 249){
				
				$emailBody = $email_template->template_vi ;
			}
			else {
				
				$emailBody = $email_template->template ;
			}
			
			$point_before_exchange =  number_format(($user_profile->p_o_u),0,".",",");
			
			$point_redemption =  number_format(($user_profile->point_redemption),0,".",",");
			
			$point_after_exchange =  number_format(($user_profile->point_after_exchange),0,".",",");
			
			$arr_key = array(
				"{f_name}","{l_name}","{member_id}","{point_before_exchange}","{point_redemption}","{list_items}","{point_after_exchange}","{pickup_place}","{pickup_place_address}"
			);
			
			$arr_replace = array(
				$user_profile->f_name,$user_profile->l_name,$user_profile->member_id,$point_before_exchange,$point_redemption,$list_items,$point_after_exchange,$user_profile->pickup_place,$user_profile->pickup_place_address
			);
			
			
			$emailBody = str_replace($arr_key, $arr_replace, $emailBody);
		
			
			$bcc  = explode(",",$email_template->email);
			
			
			$emailSubject = $email_template->subject;
			
			$mailFrom = "info@wmcvip.vn";
		
			return  JUtility::sendMail($mailFrom, "WMC VIP", $user_profile->p_email, $emailSubject, $emailBody,1,null, $bcc);
			
		}
		
	}
	/*
	 * Send email when staff approve order
	 * @Hung
	 */
	public function sendEmailWhenAprroveOrder($user_profile){
		
		$db = &JFactory::getDbo();
		$sql = "Select * FROM #__wrd_cemail WHERE id = 6" ;
		$db->setQuery($sql);
		$email_template = $db->loadObject();
		
		if(!empty($email_template)){
		
			if($user_profile->nationality == 249){
		
				$emailBody = $email_template->template_vi ;
			}
			else {
		
				$emailBody = $email_template->template ;
			}
				
				
			$arr_key = array(
		
					"{f_name}","{l_name}","{member_id}","{order_code}","{order_date}","{list_items}","{requested_outlet}","{requested_outlet_address}"
			);
				
			$order_date = (strtotime($user_profile->order_date) ? date("d-m-Y",strtotime($user_profile->order_date)) : "");
			
			$arr_replace = array(
						
					$user_profile->f_name,$user_profile->l_name,$user_profile->member_id,$user_profile->code,$order_date,$user_profile->list_items,$user_profile->requested_outlet,$user_profile->requested_outlet_address
						
			);
			$emailBody = str_replace($arr_key, $arr_replace, $emailBody);
			$bcc  = explode(",",$email_template->email);
				
				
			$emailSubject = $email_template->subject;
				
			$mailFrom = "info@wmcvip.vn";
		
			return  JUtility::sendMail($mailFrom, "WMC VIP", $user_profile->p_email, $emailSubject, $emailBody,1,null, $bcc);
		}
	}
	/*
	 * Send Email when staff reset password member
	 * @Hung
	 */
	public function sendEmailWhenStaffResetPassMember($post,$username){
		
		$mail = & JFactory::getMailer();
		$flag = false;
		$post['p_email'] = trim($post['p_email']);
		$post['alternative_email'] = trim($post['alternative_email']);
		
		if(($post['p_email'] == '') && ($post['alternative_email'] == '')) return false;
		
		if( (!$mail->ValidateAddress($post['p_email'])) && (!$mail->ValidateAddress($post['alternative_email'])) ) return false;
		
		$db = JFactory::getDbo();
		$sql = "SELECT * FROM #__wrd_cemail WHERE id = 11";
		$db->setQuery($sql);
		
		$email_template = $db->loadObject();
		
		$mailFrom = "info@wmcvip.vn";
		$emailSubject = $email_template->subject;
		
		//$emallCC = explode(",",$email_template->email);
		if($post['p_email'] != ''){
			
			$username .= " Or ".$post['p_email'];
		}
		$array_key = array(
		
			"{l_name}","{f_name}","{member_id}","{contact_email}","{password}","{user_name}"		
		);
		
		$array_replace = array(
		
			$post['f_name'],$post['l_name'],$post['member_id'],$post['p_email'],$post['member_id'].$post['year_birth'],$username
		
		);
		
		$emailBoy = str_replace($array_key, $array_replace, $email_template->template)."<hr/>".str_replace($array_key, $array_replace, $email_template->template_vi);
		
		
		
		if($post['p_email'] != ''){
			
			$rs = JUtility::sendMail($mailFrom, 'WMCVIP',$post['p_email'], $emailSubject, $emailBoy,1);
		}
		elseif($post['alternative_email'] != ''){
			
			$rs = JUtility::sendMail($mailFrom, 'WMCVIP',$post['alternative_email'], $emailSubject, $emailBoy,1,$emallCC);
		}
		return  $rs;
		
	}
	
	public function sendEmailNoticeWhenChangeProfile($post,$profile_id,$fontEnd = false){
		//Check if create new profile can not send email 
		if(isset($post["id"]) && $post["id"] == 0) return false;
		
		$user = JFactory::getUser();
		$db = JFactory::getDbo();
		$sql = "SELECT * FROM #__wrd_cemail WHERE id = 15";
		$db->setQuery($sql);
		$email_template = $db->loadObject();
		
		$query = "SELECT * FROM #__wrd_profile WHERE id = '".$profile_id."'";
		$db->setQuery($query);
		$user_profile = $db->loadObject();
		
		$nationality_old = self::getCountryById($user_profile->nationality);
		$city_old = self::getCityById($user_profile->city);
		$distric_old = self::getDistricById($user_profile->distric);
		
		$lprefer_old = self::getLpreferById($user_profile->lprefer);
		$lprefer_new = self::getLpreferById($post["lprefer"]);
		
		$user_profile->nationality    = $nationality_old->name;
		$user_profile->city           = $city_old->name;
		$user_profile->distric        = $distric_old->name;
		$user_profile->lprefer        = $lprefer_old->name;
		
		$nationality_new = self::getCountryById($post["nationality"]);
		$city_new = self::getCityById($post['city']);
		$distric_new = self::getDistricById($post["distric"]);
		
		$post["nationality"]    = $nationality_new->name;
		$post["city"]           = $city_new->name;
		$post["distric"]        = $distric_new->name;
		$post["lprefer"]        = $lprefer_new->name;
		
		$list_field_changed = "<table style='width: 100%;' border='1'><tr><th>Order</th><th>Field Name</th><th><p style='text-align: center;'>Old Value<br /></p></th><th><p style='text-align: center;'>New Value</p></th></tr>";
		
		if($email_template){
			
			$mapping_key = array();$field_name = array();
			
			$mapping_key['prefix'] = $user_profile->prefix;
			$mapping_key['f_name'] = $user_profile->f_name;	
			$mapping_key['l_name'] = $user_profile->l_name;
			$mapping_key['nationality'] = $user_profile->nationality;
					
			$mapping_key['p_email'] = $user_profile->p_email;				
			$mapping_key['alternative_email'] = $user_profile->alternative_email;		
			$mapping_key['phone'] = $user_profile->phone;				
			$mapping_key['address'] = $user_profile->address;					
						
			$mapping_key['city'] = $user_profile->city;				
			$mapping_key['distric']   = $user_profile->distric;
			$mapping_key['lprefer']   = $user_profile->lprefer;	
			$mapping_key['referer_phone'] = $user_profile->referer_phone;
			$mapping_key['referer'] = $user_profile->referer;

			$field_name['prefix']            = "Title";
			$field_name['f_name']            = "First name";
			$field_name['l_name']            = "Last name";
			$field_name['nationality']       = "Nationality";
			
			$field_name['p_email']           = "Email Contact";
			$field_name['alternative_email'] = "Personnal Email";
			$field_name['phone']             = "Mobile Phone";
			$field_name['address']           = "Contact Address";
			
			$field_name['city']              = "City";
			$field_name['distric']           = "District";
			$field_name['lprefer']           = "Language";
			$field_name['referer']           = "Referer's Email";
			$field_name['referer_phone']     = "Referer's Phone";
			
			$flag = false;
		
			foreach ($mapping_key as $key => $val) {
				
				if( ($post[$key] != $mapping_key[$key]) && (isset($post[$key]) && ($post[$key] != '')) ){
					$flag = true;break;
				}
				
			}
			
			$count = 0;
			foreach ($mapping_key as $key => $val) {
					
				if( ($post[$key] != $mapping_key[$key]) && (isset($post[$key]) && ($post[$key] != ''))  ){
					$count++;	
					$list_field_changed .= "<tr><td>".$count."</td><td>".$field_name[$key]."</td><td>".$mapping_key[$key]."</td><td>".$post[$key]."</td></tr>";
				}
			}
			
			$list_field_changed .= "</table>";
			//echo $list_field_changed."<hr/>";
			//var_dump($flag);exit;
			//*Check if have the field change -> send email notification to admin	
				if($flag){
					$emailSubject =  $email_template->subject;
					$update_by = "";
					if($fontEnd){
						
						$dob = date("d-m-Y",strtotime($user_profile->dob));
						$url_member = JURI::root()."administrator/index.php?option=com_wrd&controller=profile&id=".$user_profile->id."&layout=form&tab=card_registration_information";
						$update_by = $post["f_name"]."&nbsp;".$post["l_name"]."&nbsp;&nbsp;(<a href='".$url_member."' target='_blank' >".$user_profile->member_id."</a>)";
					
					}
					else {
						
						$dob = $post["day_birth"]."-".$post["month_birth"]."-".$post["year_birth"];
						
						$update_by = $user->username;
						
						$url_member = JURI::root()."administrator/index.php?option=com_wrd&controller=profile&id=".$user_profile->id."&layout=form&tab=card_registration_information";
						
						$update_by .= "<br/><br/> <font style='color: #000;text-decoration:underline;'> Changed on:</font> <a style='text-decoration:none;' href='".$url_member."' target='_blank' >".$user_profile->member_id."</a>"; 
						
						
					}
					
					$array_key = array("{username}","{today}","{list_field_changed}");
					
					$array_replace = array($update_by,date("d-m-Y H:i:s"),$list_field_changed);
					
					$emailBody    =  str_replace($array_key, $array_replace, $email_template->template) ;
					
					$email	      =  explode(",",$email_template->email);
					$mailFrom = "info@wmcvip.vn";
					
					if($fontEnd){
						
						return JUtility::sendMail($mailFrom, 'WMCVIP', $email, $emailSubject, $emailBody,1);
					}
					else if(!$fontEnd) {
						
						$emailReceiptBackend = array("dinh.chau@wmcvietnam.com","andy.ng@wmcvietnam.com","ngoc.tran@wmcvietnam.com","hung.phan@wmcvietnam.com");
						//"andy.ng@wmcvietnam.com","ngoc.tran@wmcvietnam.com",
						for($i= 0; $i < count($emailReceiptBackend); $i++){
							
							JUtility::sendMail($mailFrom, 'WMCVIP', $emailReceiptBackend[$i], $emailSubject, $emailBody,1);
						}
					
					}
					
				}
				else{
					
					return false;
				}
					
			}
			return false;
		}
		

	public function sendEmailNotice($post){
		$user = &JFactory::getUser();
		
		$mapping_key = array();
		$mapping_key['title'] 				= 'Title';
		$mapping_key['p_code'] 				= 'Projects';
		$mapping_key['c_code'] 				= 'Clubs';
		$mapping_key['o_code'] 				= 'Outlets';
		$mapping_key['published_up'] 		= 'Publish up';
		$mapping_key['published_down'] 		= 'Publish down';
		$mapping_key['percent'] 			= 'Percent';
		$mapping_key['cash'] 				= 'Cash';
		$mapping_key['rule'] 				= 'Rule';
		$mapping_key['lucky'] 				= 'Lucky Number';
		$mapping_key['ordinary'] 			= 'Ordinary';
		$mapping_key['multiples'] 			= 'Multiples';
		$mapping_key['priority'] 			= 'Priority';
		$mapping_key['message'] 			= 'Message';
		$mapping_key['published'] 			= 'Publish';

		$old_item = $user->current_discount;
		$emailSubject =  'WMCVIP - A discount policy has been created or modified - System report';
		
		$email	= array('dinh.chau@wmcvietnam.com','nhan.nguyen@wmcvietnam.com' );
		$mailFrom = 'WMCVIP';
		
		$emailBody = '<p><b>User Name:</b>'.$user->name.'</p>';
		$emailBody .= '<p><b>User ID:</b>'.$user->id.'</p>';
		$emailBody .= '<p><b>User Email:</b>'.$user->email.'</p>';
		
		$emailBody .= '<table width="100%">';
		$emailBody .= '<table><tr><td></td><td><b>OLD VALUE</b></td><td><b>NEW VALUE</b></td></tr>'; 
		foreach ($mapping_key as $key => $value) {
			$emailBody .=	'<tr>';
			if($key == 'ordinary' || $key == 'multiples'){
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.$old_item->$key.'</td>';
				$emailBody .= 	'<td>'.intval($post[$key]).'</td>';
			}
			elseif( $key == 'p_code'){
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.self::getProjectName($old_item->$key).'</td>';
				$emailBody .= 	'<td>'.self::getProjectName($post[$key]).'</td>';
			}
			
			elseif( $key == 'c_code'){
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.self::getClubName($old_item->$key).'</td>';
				$emailBody .= 	'<td>'.self::getClubName($post[$key]).'</td>';
			}
			
			else if($key == 'lucky'){
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.$old_item->$key.'</td>';
				$emailBody .= 	'<td>'.implode(',',unserialize($post[$key])).'</td>';
			}
			else if($key == 'o_code'){
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.self::getOutletNameList(implode(',',unserialize($old_item->$key))).'</td>';
				$emailBody .= 	'<td>'.self::getOutletNameList(implode(',',unserialize($post[$key]))).'</td>';
			}
			else if($key == 'rule'){
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.self::getListRule($old_item->$key).'</td>';
				$emailBody .= 	'<td>'.self::getListRule($post[$key]).'</td>';
			}
			else{
				$emailBody .=	'<tr>';
				$emailBody .= 	'<td><b>'.$value.':</b></td>';
				$emailBody .= 	'<td>'.$old_item->$key.'</td>';
				$emailBody .= 	'<td>'.$post[$key].'</td>';
			}
			
			$emailBody .=	'</tr>';
		}

		$emailBody .= '<table>';
		
		return JUtility::sendMail($mailFrom, 'WMCVIP', $email, $emailSubject, $emailBody,1);
	}
	
	function getListRule($rule){
		$arr = array();
		$arr['6'] = 	'Rule 0: Setup manually discount';
		$arr['1'] =		'Rule 1: Birthday';
		$arr['1a'] =	'Rule 1a: Birthday (month)';
		$arr['2'] =		'Rule 2: 1st time of using card';
		$arr['3'] =		'Rule 3: the 20th VIP member at the restaurant';
		$arr['4'] =		'Rule 4: Points reach 10,000 points or 20,000 points etc…';
		$arr['5'] =		'Rule 5: The lucky draw number';
		return $arr[$rule];
	}
	
	function getOutletNameList($outlet){
		$db = &JFactory::getDbo();
		$query = 'SELECT `name` FROM `#__wrd_outlets` where code in ('.$outlet.')';
		$rs = $db->setQuery($query)->loadObjectList();
		
		$tmp_arr = array();
		foreach ($rs as $row){
			$tmp_arr[] = $row->name;
		}
		
		return implode(', ', $tmp_arr);
	}
	
	function getProjectName($id){
		
		if(strlen($id) == 1)
			$id = '0'.$id;
		
		$db = &JFactory::getDbo();
		$query = 'SELECT `name` FROM `#__wrd_projects` where code in ('.$id.')';
		$rs = $db->setQuery($query)->loadObjectList();
		
		$tmp_arr = array();
		foreach ($rs as $row){
			$tmp_arr[] = $row->name;
		}
		
		return implode(', ', $tmp_arr);
	}
	
	function getTotalPointOfRedemption($code = ''){
		
		if($code == '') return ;
		$sql = "SELECT SUM(point) as total FROM #__wrd_redemption WHERE code = '".$code."'";
		$db = &JFactory::getDbo();
		//echo $sql;
		$db->setQuery($sql);
		return $db->loadObject();
		
	}
   function getRecordOfRedemptionByCode($code = ''){
		
		if($code == '') return ;
		
		$code = trim(strip_tags($code));
		
		$sql = "SELECT * FROM #__wrd_redemption WHERE code = '".$code."'";
		$db = &JFactory::getDbo();
		//echo $sql;
		$db->setQuery($sql);
		return $db->loadObjectList();
   }
	function getClubName($id){
		
		if(strlen($id) == 1)
			$id = '0'.$id;
		
		$db = &JFactory::getDbo();
		$query = 'SELECT `name` FROM `#__wrd_club` where code in ('.$id.')';
		$rs = $db->setQuery($query)->loadObjectList();
		
		$tmp_arr = array();
		foreach ($rs as $row){
			$tmp_arr[] = $row->name;
		}
		
		return implode(', ', $tmp_arr);
	}
	
	function getPointsEarn($id){
		if($id == 0)
			return 0;
		else{
			$db = JFactory::getDbo();
			$query = " SELECT sum(point) as total FROM #__wrd_point `t` WHERE `t`.user_id = '".$id."' AND `t`.point > 0";
			$db->setQuery($query);
			$rs = $db->loadObject();
		}
		return intval($rs->total);
	}
	/*
	 * @Get Record Outlet by Code of outlets
	 * @Hung Phan
	 */
	function getOutlet($ocode){
		
		$db = &JFactory::getDbo();
		
		$ocode = trim(strip_tags($ocode));
		 
		$query = "SELECT * FROM #__wrd_outlets where code = '".$ocode."'";
		
		return  $db->setQuery($query)->loadObject();	
	}
	
	
	function getPoints($id){
		
		if($id == 0)
			return 0;
		else{
			
			$db = &JFactory::getDbo();
			$query = 'SELECT user_id,year,month,point,point_life_time FROM #__wrd_points_summary WHERE user_id='.$id.' ORDER BY year DESC,month DESC LIMIT 1';
			$db->setQuery($query);
			$rs = $db->loadObject();
			
		}
		return $rs;
	}
	
	//get total transaction of member_id from #__wrd_spending_summary
	function getTotalTransaction($member_id){
		
		if($member_id == 0)
			return 0;
		else{
			$db = JFactory::getDbo();
			$query = 'SELECT member_id,year,month,total FROM #__wrd_spending_summary WHERE member_id='.$member_id.' ORDER BY year DESC,month DESC LIMIT 1';
			$db->setQuery($query);
			$rs = $db->loadObject();
		}
		
		return $rs;
	}
	
	public function activeEmail($data = array() ){
		$config = JFactory::getConfig();
  		$params = JComponentHelper::getParams('com_users');
  		$useractivation = 1;
  		$cc = '' ;
  		$data['siteurl'] = JURI::base();
  		
		if ($useractivation == 2){
			// Set the link to confirm the user email.
			$uri = JURI::getInstance();
			$base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
			$data['activate'] = $data['siteurl'].JRoute::_('index.php?option=com_wrd&task=profile.activate&token='.$data['activation'].'&key='.$data['password_clear'], false);
  			
			$temp = JText::_('COM_USERS_EMAIL_ACCOUNT_DETAILS') ;
			$emailSubject	= JText::sprintf(
  	  			$temp,
				$data['name'],
				$data['sitename']
			);
  			
			$temp = JText::_('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY') ;
			$emailBody = JText::sprintf(
  	  			$temp,
				$data['name'],
				$data['sitename'],
				$data['siteurl'].'index.php?option=com_wrd&task=profile.activate&token='.$data['activation'].'&key='.$data['password_clear'],
				$data['siteurl'],
				$data['username'],
				$data['password_clear']
			);
			
		}else if ($useractivation == 1){
			// Set the link to activate the user account.
			$uri = JURI::getInstance();
			$base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
			$data['activate'] = $data['siteurl'].JRoute::_('index.php?option=com_wrd&task=profile.activate&token='.$data['activation'].'&key='.$data['password_clear'], false);
  	
			$temp = JText::_('COM_USERS_EMAIL_ACCOUNT_DETAILS') ;
			$emailSubject	= JText::sprintf(
				$temp,
  				$data['name'],
  				$data['sitename']
  			);
  			
			//$temp = JText::_('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY') ;
			$db = JFactory::getDbo();
			$sql = ' select * from #__wrd_cemail where `action` = "registration"' ;
			$db->setQuery($sql) ;
			$rs = $db->loadObject();
			
			$temp = $rs->template ;
			$temp .= '<p><hr /></p>' ;
			$temp .= $rs->template_vi ;
			$cc = explode(',', $rs->email) ;
			$active_link = '<a href="'.$data['siteurl'].'index.php?option=com_wrd&task=profile.activate&token='.$data['activation'].'&key='.$data['password_clear'].'">'.$data['siteurl'].'index.php?option=com_wrd&task=profile.activate&token='.$data['activation'].'&key='.$data['password_clear'].'</a>' ;
			
			$temp = str_replace('{username}', $data['name'], $temp);
			$temp = str_replace('{email}', $data['email'], $temp);
			$temp = str_replace('{active_link}', $active_link, $temp);
			$temp = str_replace('{link}', $data['siteurl'], $temp);
			$temp = str_replace('{username}', $data['name'], $temp);
			$temp = str_replace('{password}', $data['password_clear'], $temp);
			
			$emailBody = JText::sprintf(
	  	  		$temp,
				$data['name'],
				$data['sitename'],
				$data['siteurl'].'index.php?option=com_wrd&task=profile.activate&token='.$data['activation'].'&key='.$data['password_clear'],
				$data['siteurl'],
				$data['username'],
				$data['password_clear']
			);
			

		}else{
			$temp = JText::_('COM_USERS_EMAIL_ACCOUNT_DETAILS') ;
			$emailSubject	= JText::sprintf(
  	  			$temp,
				$data['name'],
				$data['sitename']
			);
  	
			$temp = JText::_('COM_USERS_EMAIL_REGISTERED_BODY') ;
			$emailBody = JText::sprintf(
  	  			$temp,
				$data['name'],
				$data['sitename'],
				$data['siteurl']
			);
		}
		
		$emailBody = str_replace('{line-break}', '<br />', $emailBody);
		
		$data['mailfrom'] = 'info@wmcvip.vn';
		$data['fromname'] = 'WMC Vip';
		
		$return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody,true);

  		
		// Check for an error.
		if ($return !== true) {
			$this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED'));
  	
			// Send a system message to administrators receiving system mails
			$db = JFactory::getDBO();
			$q = "SELECT id
				FROM #__users
				WHERE block = 0
  	  			AND sendEmail = 1";
			
  			$db->setQuery($q);
  			$sendEmail = $db->loadResultArray();
  			
			if (count($sendEmail) > 0) {
  				$jdate = new JDate();
  				// Build the query to add the messages
  				$q = "INSERT INTO `#__messages` (`user_id_from`, `user_id_to`, `date_time`, `subject`, `message`)
					VALUES ";
  				$messages = array();
  				foreach ($sendEmail as $userid) {
  					$messages[] = "(".$userid.", ".$userid.", '".$jdate->toMySQL()."', '".JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT')."', '".JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username'])."')";
  				}
  				$q .= implode(',', $messages);
  				$db->setQuery($q);
  				$db->query();
  			}
  			return false;
  		}
  		return true;
	}
	
	//gift redemption report new
	//@author hung phan
	public function getProductByCodeRedem($code){
		$sql = "SELECT `pr`.name AS productName,`pr`.cost_pricing,
				`po`.point,`po`.transaction,
				`r`.quantity
				FROM #__wrd_redemption AS `r`
				INNER JOIN #__wrd_point AS `po` ON `po`.redemption_id = `r`.code
				INNER JOIN #__wrd_products AS `pr` ON `pr`.id = r.product_id
				INNER JOIN #__wrd_transaction AS t ON t.transaction_id = `po`.transaction
				WHERE `po`.redemption_id = '".$code."'
				GROUP BY productName
		";
		$db = JFactory::getDbo();
		//echo $sql;
		$db->setQuery($sql);
		return  $db->loadObjectList();
	}
	
	//Ham nay dung trong gift redemption report new
	//@author hung phan
	public function totalPointByCodeRedem($code){
		$sql = "SELECT sum(point) as total FROM  #__wrd_point WHERE redemption_id = '".$code."'
		";
		$db = JFactory::getDbo();
		//echo $sql;
		$db->setQuery($sql);
		return  $db->loadObject();
	}
	//Get Product la voucher,dung check trong file profile/addredemption.php 
	public function getProductVoucher(){
		$sql = "
            SELECT 
                `t`.id
            FROM #__wrd_products `t`
            WHERE `t`.published = 1
                  AND ((YEAR(`t`.published_up) = 0
                        AND YEAR(`t`.published_down) = 0)
                        OR (`t`.published_up <= '".date('Y-m-d')."'
                            AND `t`.published_down >= '".date('Y-m-d')."'))
			AND voucher = 1				
        ";
		$db = JFactory::getDbo();
		$db->setQuery($sql);
		return $db->loadObjectList();
		
	}
	/*Get Product by Id of Product
	 * @Hung
	 */
	public function getProduct($id){
		
		$sql = "SELECT * FROM #__wrd_products WHERE id = '".$id."'";
		$db  = JFactory::getDbo();
		$db->setQuery($sql);
		return $db->loadObject();
		
	}
	
	/*Check Product availabe
	 * @Hung version 1.0
	 * If Prouduct available , Return int  = 1 , else return message erros
	*/
	/*
	public function checkProduct($idProduct,$qty){
	
		$sql = "SELECT name,quantity FROM #__wrd_products WHERE id = '".$idProduct."' AND published = 1";
		$db  = JFactory::getDbo();
		$product = $db->setQuery($sql)->loadObject();
		if((int)$product->quantity < (int)$qty) 
		{	
			$lang =& JFactory::getLanguage();
			
			$product->name = unserialize($product->name);
			
			$productname = $product->name[$lang->getTag()];
			 
			$errortext = JText::sprintf('WRD_PROMOTION_CURRENT_QUALITY_ERROR',$productname,$product->quantity,$qty);
			
			return $errortext;
		}
		else return 1;	
	
	}*/
	
	public function updateRedemptionReport($arr,$type=1){
		//echo '<pre>';print_r($arr);die;
		//echo $arr[0]['code']."<br/>";
		$sql = "SELECT count(*) as total FROM #__wrd_redemption_report WHERE code_redemption='".$arr[0]['code']."'";
		//$sql = "SELECT count(*) as total FROM #__wrd_point";
		$db = JFactory::getDbo();
		$db->setQuery($sql);
		$rows = $db->loadObject();
		//echo '<pre>';print_r($rows);
		if($rows->total == 0){
			foreach($arr as $k){
				$q = "SELECT cost_pricing FROM #__wrd_products WHERE id='".$k['product_id']."'";
				$db->setQuery($q);
				$cost = $db->loadObject();
				$obj = new stdClass;
				$obj->outlet = $k['outlet'];
				$obj->outletName = $k['outletName'];
				$obj->product_id = $k['product_id'];
				$obj->product_cost = $cost->cost_pricing;
				$obj->productName = $k['product'];
				$obj->approved = $k['approved'];
				$obj->status_of_redemption = $k['status_of_redemption'];
				$obj->exchange_date = $k['exchange_date'];
				$obj->pick_up_date = $k['pick_up_date'];
				$obj->status_of_redemption_date = $k['status_of_redemption_date'];
				$obj->approved_date = $k['approved_date'];
				$obj->quantity = $k['quantity'];
				$obj->percent = $k['percent'];
				$obj->code_redemption = $k['code'];
				$db->insertObject('#__wrd_redemption_report', $obj);
			}
		}
		else {
			if($type==2):
				foreach($arr as $k){
					
					$sql = "UPDATE #__wrd_redemption_report SET
					outletName = '".$k['outletName']."',
					product_id = '".(int)$k['product_id']."',
					productName = '".$k['product']."',
					approved = '".(int)$k['approved']."',
					status_of_redemption = '".$k['status_of_redemption']."',
					exchange_date = '".$k['exchange_date']."',
					pick_up_date = '".$k['pick_up_date']."',
					status_of_redemption_date = '".$k['status_of_redemption_date']."',
					approved_date = '".$k['approved_date']."',
					quantity = '".(int)$k['quantity']."',
					percent = '".$k['percent']."',
					code_redemption = '".$k['code']."'
					WHERE (outlet = '".(int)$k['outlet']."') AND (product_id = '".(int)$k['product_id']."')"; 
					$db->setQuery($sql);
					$db->query();
				}
			endif;
		}
	}
	public static function getUserProfile($id,$type='userid'){
		
		if($id == 0)
			return null;
		$db = &JFactory::getDbo();
		
		if($type == 'userid')
		{
			$query = 'SELECT * FROM #__wrd_profile WHERE user_id = '.$id;
			//echo $query;
		}	
		else if($type == 'id')
			$query = 'SELECT * FROM #__wrd_profile WHERE id = '.$id;
			
		else if($type == 'member_id' || $type == 'memberid')
			$query = 'SELECT * FROM #__wrd_profile WHERE member_id = '.$id;
		
		$db->setQuery($query);
		return $db->loadObject();
	}
	
	public function getConfigFieldRegistration(){
	
		$db = JFactory::getDBO();
		$query = 'SELECT caption, f_tip,field  FROM  #__wrd_crpoint';
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		
		if(count($rs) > 0){
			$arr = array();
			foreach($rs as $item){
				$arr[$item->field]['caption'] = $item->caption;
				$arr[$item->field]['f_tip'] = $item->f_tip;
			}
		}
		return $arr;
	}
    
    public function getDistrict()
    {
        $model = &JModelLegacy::getInstance('distric','WrdModel');
        $models = array();    
        $models = $model->getList();
        return $models;
    }        
    
    public function getIdDistrictValueByName($listDistrict, $name){                
        $name = trim($name);
        if($name != '')
        {
            foreach($listDistrict as $item)                                                       
            {
                //$item->text = trim($item->text);
                if($item->text == $name)
                {
                    return $item->value;
                }
            }                                    
        }
        return 0;
    }
	
    public function getCity()
    {
        $model = &JModelLegacy::getInstance('city','WrdModel');
        $models = array();    
        $models = $model->getList();
        return $models;
    }
    
    public function correctCityName($name)
    {
        $name = trim($name);
        if(
            $name == 'Ba Ria' || $name == 'Ba Ria - Vung Tau' || 
            $name == 'Ba Ria Vung Tau' || $name == 'Ba Ria- Vung Tau' || 
            $name == 'Ba Ria-Vung Tau Province'
        )
        {
            $name = 'Ba Ria - Vung Tau';
        }
        else if($name == 'BacBinh')
        {
            $name = 'Bac Ninh';
        }
        else if($name == 'Ben Tre City')
        {
            $name = 'Ben Tre';
        }
        else if($name == 'Bien Hoa City' || $name == 'Bien Hoa City,' || $name == 'Bien Hoa,' || $name == 'BienHoa')
        {
            $name = 'Bien Hoa';
        }
        else if($name == 'Binh Dinh')
        {
            $name = 'Binh dinh';
        }
        else if($name == 'Binh Duong' || $name == 'Binh Duong Province' || $name == 'Binh Duong Province,' || $name == 'BinhDuong')
        {
            $name = 'Binh Duong';
        }
        else if($name == 'CaMau')
        {
            $name = 'Ca Mau';
        }
        else if($name == 'CanTho')
        {
            $name = 'Can Tho';
        }
        
        
        else if($name == 'Da Nang City' || $name == 'DaNang')
        {
            $name = 'Da Nang';
        }
        else if($name == 'Dak Lak')
        {
            $name = 'dak Lak';
        }
        else if($name == 'Dongnai')
        {
            $name = 'Dong Nai';
        }
        else if($name == 'Ha Noi City' || $name == 'HaNoi')
        {
            $name = 'Ha Noi';
        }
        
        
        else if($name == 'HaiPhong')
        {
            $name = 'Hai Phong';
        }
        else if($name == 'Hcm' || $name == 'HCMC')
        {
            $name = 'Ho Chi Minh';
        }
        else if($name == 'Lam Dong Province')
        {
            $name = 'Lam Dong';
        }
        else if($name == 'Long An Province')// toi Nha Trang
        {
            $name = 'Long An';
        }
        else if($name == 'Quang Nam Province')
        {
            $name = 'Quang Nam';
        }
        
        else if($name == 'Qui Nhon,' ||$name == 'Quy Nhon' || $name == 'QuyNhon')
        {
            $name = 'Quy Nhon';
        }
        else if($name == 'SocTrang')
        {
            $name = 'Soc Trang';
        }
        else if($name == 'Tay Ninh Province' || $name == 'TayNinh')
        {
            $name = 'Tay Ninh';
        }
        else if($name == 'Tien Giang Province')
        {
            $name = 'Tien Giang';
        }
        
        else if($name == 'Tra Vinh Province')
        {
            $name = 'Tra Vinh';
        }
        else if($name == 'VinhLong')
        {
            $name = 'Vinh Long';
        }
        else if($name == 'Vung Tau' || $name == 'VungTau')
        {
            $name = 'Ba Ria - Vung Tau';
        }
        //$name = strtolower($name);
        
        return $name;
    }
    
	public function getCityValueByName($lists, $name){
		                
        //$name = WrdHelper::correctCityName($name);
        
        if($name != ''){
            foreach($lists as $item){
                // Remove district
                $item->text = trim($item->text);
                if(($item->text) == ($name)){
                    return $item->value;
                }
            }                                    
        }
        
        return 0;
    }
    
    public function getJobTitleOcupation($name)
    {
        $result = array(-1, 'other', $name);
        $name = strtolower($name);
        
        if(stristr($name, 'senior') != false) { $result[0] = 's';   }
        else if(stristr($name, 'deputy') != false) { $result[0] = 'd';   }        
        else if(stristr($name, 'vice') != false) { $result[0] = 'v';   }
        
        else if(stristr($name, 'assistant') != false) { $result[0] = 'a';   }
        else if(stristr($name, 'admin') != false) { $result[0] = 'm';   }        
        else if(stristr($name, 'academic') != false) { $result[0] = 'e';   }
        else if(stristr($name, 'account') != false) { $result[0] = 'c';   }
        
        if(stristr($name, 'ceo') != false) { $result[1] = 1;   }
        else if(stristr($name, 'chairman') != false) { $result[1] = 1;   }
        else if(stristr($name, 'president') != false) { $result[1] = 2;   }
        else if(stristr($name, 'director') != false) { $result[1] = 3;   }
        
        else if(stristr($name, 'manager') != false) { $result[1] = 4;   }
        else if(stristr($name, 'officer') != false) { $result[1] = 5;   }
        else if(stristr($name, 'advisor') != false) { $result[1] = 6;   }
        else if(stristr($name, 'executive') != false) { $result[1] = 7;   }
        return $result;
    }
    
    public function importNationality($name)
    {
        $result = 0;
        $name = strtoupper($name);
        switch($name)
        {
            case 'AUS': $result = 15;  break;
            case 'AUT': $result = 16;  break;
            case 'BEL': $result = 24;  break;
            case 'CHI': $result = 243;  break;
            case 'ENG': $result = 243;  break;
            
            case 'FIJ': $result = 80;  break;
            case 'FIL': $result = 185;  break;
            case 'FRA': $result = 82;  break;
            case 'GER': $result = 90;  break;
            case 'IND': $result = 111;  break;
            
            case 'INO': $result = 112;  break;
            case 'ITA': $result = 118;  break;
            case 'JAP': $result = 121;  break;
            case 'JPN': $result = 215;  break;
            case 'KOR': $result = 128;  break;
            
            case 'MAL': $result = 145;  break;
            case 'NOR': $result = 176;  break;
            case 'NZL': $result = 169;  break;
            case 'POL': $result = 187;  break;
            case 'RUS': $result = 193;  break;
            
            case 'SIN': $result = 208;  break;
            case 'SWE': $result = 222;  break;
            case 'SWISS': $result = 223;  break;
            case 'TAI': $result = 225;  break;
            case 'THA': $result = 228;  break;            
            
            case 'THAI': $result = 228;  break;
            case 'TUR': $result = 236;  break;
            case 'UAE': $result = 242;  break;
            case 'UN': $result = 0;  break;
            case 'USA': $result = 244;  break;  
            case 'VIE': $result = 249;  break;
        }
        return $result;
    }
    
    public function importPickUpAt($name, $db)
    {
        $result = '';
        $name = trim($name);
        
        switch($name)
        {
            case 'Amigo':    
                $result = 111;    break;    
                
            case 'CCAD':    
                $result = 221;    break;    
            
            case 'CCNH':    
                $result = 131;    break;    
            
            case 'Duc Bao':    
            case 'Gartenstadt':
                $result = 121;    break;    
            
            case 'Kissho':    
                $result = 181;    break;    
            
            case 'Ngan Dinh':    
                $result = 211;    break;    
            
            case 'Spa':    
                $result = 22;    break;    
            
            case 'TOTT': 
            case '24th Floor':
                $result = 191;    break;    
                
            case 'Disco':    
                $result = 0;    break;    

            case 'Sherwood':
            case 'Sherwood (9F)':
			case 'Sherwood (FO)':
			case 'Sherwood (Unit 8E)':
				$result = 'b80';    
				break;
            default:
               	$query = 'SELECT `code` FROM #__wrd_outlets where `name` = "'.$name.'"';
               	//file_put_contents('log_outlet.txt', print_r($query,1), FILE_APPEND);
               	$db->setQuery($query);
               	$result = $db->loadObject()->code;
                break;
        }
        return $result;
    }
    
    public function checkDuplicatePickUpAt($name){
        $db = &JFactory::getDbo();
        $query = "SELECT COUNT(*) FROM #__wrd_outlets WHERE `name` = '".strval($name)."'";
        $db->setQuery($query);        
        $isExist = $db->loadResult();
        return $isExist;
    }
    
    public function importSource($name, $db)
    {
        $result = 0;
        $name = trim($name);
        
        switch($name)
        {
            case 'Amigo':  
                $result = 1;    break;    
                
            case 'CCAD':  
                $result = 5;    break;    
            
            case 'CCNH':    
                $result = 2;    break;    
            
            case 'Duc Bao':    
            case 'Gartenstadt':
                $result = 3;    break;    
            
            case 'Kissho':    
                $result = 4;    break;    
            
            case 'Ngan Dinh':    
                $result = 6;    break;    
            
            case 'Spa':    
                $result = 8;    break;    
            
            case 'TOTT':    
                $result = 7;    break;    
                
            case 'Disco':    
                $result = 9;    break;    
                
            default:
                if($name != '' && WrdHelper::checkDuplicateSource($name) <= 0)
                {
                    $obj = new stdClass();
                    $obj->name = strval($name);                
                    $obj->des = $name;
                    $obj->published = 1;
                    $obj->created_id = 42;
                    $obj->created_date = date('Y-m-d h:i:s', time());
                    $db->insertObject('#__wrd_sources', $obj);  
                    $result = $db->insertid();     
                }
                break;
        }
        return $result;
    }
    
    public function checkDuplicateSource($name){
        
        $db = &JFactory::getDbo();
        $query = "SELECT COUNT(*) FROM #__wrd_sources WHERE `name` = '".strval($name)."'";
        $db->setQuery($query);        
        $isExist = $db->loadResult();
        return $isExist;
    }
    
    public function getFiles($id,$user,$type = 'image'){
		$db = JFactory::getDbo();

		if($type != 'profile'){
			$query = 'SELECT * FROM #__wrd_file WHERE product_id = '.$id.' AND type="'.$type.'"';
			$db->setQuery($query);
			$rs = $db->loadObjectList();
		}else{
			$query = 'SELECT * FROM #__wrd_file WHERE product_id = '.$id.' AND user_id = '.$user.' AND type="'.$type.'" LIMIT 0,1';
			
			$db->setQuery($query);
			$rs = $db->loadObject();
		}
		return $rs;
	}
	
	public function checkStep($request){
		if(
			isset($request['prefix']) &&
			isset($request['dob']) &&
			isset($request['f_name']) &&
			isset($request['l_name']) &&
			isset($request['city']) &&
			isset($request['distric'])&& 
			isset($request['nationality'])&&
			isset($request['p_email'])&&
			isset($request['alternative_email'])&&
			isset($request['phone'])&&
			isset($request['address'])&&
			isset($request['country'])&&
			isset($request['city'])&&
			isset($request['distric'])&&
			isset($request['pick_up_at'])&&
			isset($request['referer'])
		){
			return 2;
		}
		if(
			isset($request['status']) &&
			isset($request['website']) &&
			isset($request['skype']) &&
			isset($request['yahoo']) &&
			isset($request['gtalk']) &&
			isset($request['msn']) && 
			isset($request['other_hobbies'])
		){
			return 3;
		}
		if(
			isset($request['job']) &&
			isset($request['department']) &&
			isset($request['industry']) &&
			isset($request['company_name'])&&
			isset($request['c_addr']) &&
			isset($request['c_info']) &&
			isset($request['c_country']) &&
			isset($request['c_city']) &&
			isset($request['c_distric'])
		){
			return 4;
		}
		if(
			isset($request['education']) &&
			isset($request['o_club']) &&
			isset($request['income']) && 
			isset($request['bation']) &&
			isset($request['o_education']) &&
			isset($request['o_bation'])
			 
		){
			return 5;
		}
	}
	
    /*
     * If type = registration -> id = id of outlet code
     * Else: id = id transaction 
	 * function convert() in administrator/com_wrd/controller.php call this
     */
	function machPoint($id, $type='registration'){
	
		$db = JFactory::getDBO();
		if($type == 'registration'){
			$user = &JFactory::getUser();
			$trans = new stdClass();
			$trans->outlet = $id;
			$trans->date_receipt = '0000-00-00 00:00:00';
			$trans->food = 0;
			$trans->beverage = 0;
			
			$profile = WrdHelper::getUserProfile($user->id);
			$profile->project_id = 0;
			$profile->club_id = 0;
		}
		else{
			//get transaction detail
			
			$query = 'SELECT * FROM #__wrd_transaction WHERE id = '.$id;
			$db->setQuery($query);
			$trans = $db->loadObject();
			
			//get User detail
			$profile = WrdHelper::getUserProfile($trans->vip_number,'member_id');
		}
		
		//get all point config mach 
		$query = '
			SELECT * FROM #__wrd_cpoint 
			WHERE p_code = '.$profile->project_id .' 
			AND c_code ='.$profile->club_id .'
			AND o_code ='.$trans->outlet.' 
			AND published = 1  
			AND published_down >= "'.date('Y-m-d',strtotime($trans->date_receipt)).'" 
			AND published_up <= "'.date('Y-m-d',strtotime($trans->date_receipt)).'"
			ORDER BY id DESC
		';
		
		//file_put_contents('querylog.log', print_r($query.PHP_EOL,1),FILE_APPEND);
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		
		$matchID = "";
		if(count($rs) > 0){
			foreach ($rs as $item){
			
				$ThoaDieuKienGioiTinh = 1;
				$ThoaDieuKienThoiGian = 1;
				$ThoaDieuKienNgayTrongTuan = 1;
				$ThoaDieuKienGio = 1;
			
				$n=0;
				// Kiem tra lap thu hai hang tuan
				if ($item->mon_r == 1){
					if(date('l',strtotime($trans->date_receipt)) != "Monday"){
						$dayArray[$n] = 0;
					} else {
						$dayArray[$n] = 1;
					}
					$n++;
				}
				// Kiem tra lap thu ba hang tuan
				if ($item->tue_r == 1){
					if(date('l',strtotime($trans->date_receipt)) != "Tuesday"){
						$dayArray[$n] = 0;
					} else {
						$dayArray[$n] = 1;
					}
					$n++;
				}
				// Kiem tra lap thu tu hang tuan
				if ($item->wed_r == 1){
					if(date('l',strtotime($trans->date_receipt)) != "Wednesday"){
						$dayArray[$n] = 0;
					} else {
						$dayArray[$n] = 1;
					}
					$n++;
				}
				// Kiem tra lap thu nam hang tuan
				if ($item->thu_r == 1){
					if(date('l',strtotime($trans->date_receipt)) != "Thursday"){
						$dayArray[$n] = 0;
					} else {
						$dayArray[$n] = 1;
					}
					$n++;
				}
				// Kiem tra lap thu sau hang tuan
				if ($item->fri_r == 1){
					if(date('l',strtotime($trans->date_receipt)) != "Friday"){
						$dayArray[$n] = 0;
					} else {
						$dayArray[$n] = 1;
					}
					$n++;
				}
				// Kiem tra lap thu bay hang tuan
				if ($item->sat_r == 1){
					if(date('l',strtotime($trans->date_receipt)) != "Saturday"){
						$dayArray[$n] = 0;
					} else {
						$dayArray[$n] = 1;
					}
					$n++;
				}
				// Kiem tra lap chu nhat hang tuan
				if ($item->sun_r == 1){
					if(date('l',strtotime($trans->date_receipt)) != "Sunday"){
						$dayArray[$n] = 0;
					} else {
						$dayArray[$n] = 1;
					}
					$n++;
				}
				if($n != 0) $ThoaDieuKienNgayTrongTuan = 0;
				for($i=0;$i<$n;$i++){
					$ThoaDieuKienNgayTrongTuan = $ThoaDieuKienNgayTrongTuan || $dayArray[$i];
				}		
				
				//check affternoon,morning,evening
				$j=0;
				if($item->m==1){
					if(($item->f_m_hour <= date('H',strtotime($trans->date_receipt))) && ($item->t_m_hour >= date('H',strtotime($trans->date_receipt))) ){
						$hourArray[$j] = 1;
					} else {
						$hourArray[$j] = 0;
					}
					$j++;
				}
				if($item->a==1){
					if(($item->f_a_hour <= date('H',strtotime($trans->date_receipt))) && ($item->t_a_hour >= date('H',strtotime($trans->date_receipt))) ){
						$hourArray[$j] = 1;
					} else {
						$hourArray[$j] = 0;
					}
					$j++;
				}
				if($item->e==1){
					if(($item->f_e_hour <= date('H',strtotime($trans->date_receipt))) && ($item->t_e_hour >= date('H',strtotime($trans->date_receipt))) ){
						$hourArray[$j] = 1;
					} else {
						$hourArray[$j] = 0;
					}
					$j++;
				}
				
				if($j != 0) $ThoaDieuKienGio = 0;
				for($i=0;$i<$j;$i++){
					$ThoaDieuKienGio = $ThoaDieuKienGio || $hourArray[$i];
				}
				
				// Kiem tra dieu kien gioi tinh
				if($profile->prefix == 'Ms.' || $profile->prefix == 'Mrs.')
					$profile->sex = 'female';
				else if($profile->prefix == 'Mr.')
					$profile->sex = 'male';
				
				if(strtolower($item->gender) != "0"){
					// Chua chon gender trong profile, nen kiem tra gioi tinh dua vao title
					if($profile->gender == "0"){
						if (strtolower($item->gender) != $profile->sex){
							$ThoaDieuKienGioiTinh = 0;
						}
					}
					else {
						if (strtolower($item->gender) != strtolower($profile->gender)){
							$ThoaDieuKienGioiTinh = 0;
						}
					}
				}
				if($item->published_down != '0000-00-00' && $item->published_up != '0000-00-00'){
					if( strtotime($item->published_down.' 23:59:59') > strtotime($trans->date_receipt) && strtotime($trans->date_receipt) > strtotime($item->published_up.' 00:00:01') ){
						$ThoaDieuKienThoiGian = 1;
					} else {
						$ThoaDieuKienThoiGian = 0;
					}
				}
				
				if($ThoaDieuKienGioiTinh && $ThoaDieuKienThoiGian && $ThoaDieuKienNgayTrongTuan && $ThoaDieuKienGio) {
					$matchID = $item->id;
					break;
				}
			}			
		}
	
		$obj = new stdClass();
		
		if(intval($matchID) != 0){
			$query = 'SELECT * FROM #__wrd_cpoint WHERE id = '.$matchID;
			$db->setQuery($query);
			
			$rs=$db->loadObject();
			
			$obj->f = $rs->f;
			$obj->b = $rs->b;
			$obj->o = $rs->o;
			$obj->point = $rs->point;
			$obj->user_id = $profile->user_id;
			$obj->tran = $trans->transaction_id;
		
			file_put_contents('logs-wrd'.DS.'point'.DS.date("Y-m-d").'-point-converted.txt', json_encode($obj)."\n", FILE_APPEND);
		}
			
		return $obj;
	}
	
    public static function outletPoint($db, $transaction)
    {
        /************ Init ************/
        //$currentDate = date('Y-m-d');
        $currentDate = $transaction->date_receipt;
		
		$hours = array(0,0,0);
        $dateReceipt = 0;
        
        if($transaction->date_receipt != '') {
            $transaction->date_receipt = explode(' ', $transaction->date_receipt);
            $dateReceipt = $transaction->date_receipt[0];
            $hours = explode(':', $transaction->date_receipt[1]);
        }
        
        $userProfile = "SELECT `t`.gender, `t`.user_id FROM #__wrd_profile `t` 
        		WHERE `t`.member_id = '".$transaction->vip_number."'";
        $db->setQuery($userProfile);
        $userProfile = $db->loadObject();
        $userId = $userProfile->user_id;
        $userProfile = $userProfile->gender;
        
        /************ Get all point config mach ************/
        
		$query = "
            SELECT *
            FROM #__wrd_cpoint `t`
            WHERE p_code = '01'
                  AND c_code = '01'
                  AND o_code = '".$transaction->outlet."'
                  AND published = 1
                  AND ((YEAR(`t`.published_up) = 0
                        AND YEAR(`t`.published_down) = 0)
                        OR ('".$currentDate."' >= `t`.published_up
                            AND '".$currentDate."' <= `t`.published_down))
			
		";

        $query .= " ORDER BY `t`.published_up ASC ";
        
		$db->setQuery($query);
        $models = $db->loadObjectList();
       
        $points = array();
        if(count($models) == 1){
            $points = array('point'=>$models[0]->point);
        }
        else
        {
            $points[] = array('point'=>$models[0]->point);
            unset($models[0]);
            foreach($models as $item){
                $isMatch = array(
                    'time' => false,
                    'food' => false,
                    'beverage' => false,
                    'other' => false,
                    'gender' => false,
                    'daily' => false
                );
                
                /**** Check time ****/
                {
                    if($item->m == 0 && $item->a == 0 && $item->e == 0){
                        $isMatch['time'] = true;
                    }
                    else if($item->m == 1 && ($item->f_m_hour <= $hours[0] && $item->t_m_hour >= $hours[0] )){
                        $isMatch['time'] = true;                         
                    }
                    else if($item->a == 1 && ($item->f_a_hour <= $hours[0] && $item->t_a_hour >= $hours[0] )){
                        $isMatch['time'] = true;                         
                    }
                    else if($item->e == 1 && ($item->f_e_hour <= $hours[0] && $item->t_e_hour >= $hours[0] )){
                        $isMatch['time'] = true;                         
                    }
                }
                
                /**** Check type ****/
                {
                    if($item->f == 0) {
                        $isMatch['food'] = true;
                    }
                    else if($item->f == 1 && $transaction->food != ''){
                        $isMatch['food'] = true;    
                    }
                    
                    if($item->b == 0) {
                        $isMatch['beverage'] = true;
                    }
                    else if($item->b == 1 && $transaction->beverage != ''){
                        $isMatch['beverage'] = true;    
                    }
                    
                    if($item->o == 0) {
                        $isMatch['other'] = true;    
                    }
                    else if($item->o == 1 && $transaction->other != ''){
                        $isMatch['other'] = true;    
                    }   
                }
                
                /**** Check Gender ****/
                {
                    if($item->gender == 0){
                        $isMatch['gender'] = true;
                    }
                    else if($item->gender != 0) {
                        if($userProfile == 'Ms.' || $userProfile == 'Mrs.')
                            $userProfile = 'female';
                        else if($userProfile == 'Mr.')
                            $userProfile = 'male';
                        else
                            $userProfile = 'other';
                            
                        if($item->gender == $userProfile) {
                            $isMatch['gender'] = true;   
                        }
                    }    
                }
                
                /**** Check daily ****/
                {
                    //var_dump($item->mon, $item->mon_r, $item->tue, $item->tue_r, $item->wed, $item->wed_r, $item->thu, $item->thu_r, $item->fri, $item->fri_r, $item->sat, $item->sat_r, $item->sun, $item->sun_r );
                    
                    if(
                        $item->mon == '0000-00-00' && $item->mon_r == '0' &&
                        $item->tue == '0000-00-00' && $item->tue_r == '0' &&
                        $item->wed == '0000-00-00' && $item->wed_r == '0' &&
                        
                        $item->thu == '0000-00-00' && $item->thu_r == '0' &&
                        $item->fri == '0000-00-00' && $item->fri_r == '0' &&
                        $item->sat == '0000-00-00' && $item->sat_r == '0' &&
                        $item->sun == '0000-00-00' && $item->sun_r == '0' 
                    ) {
                        $isMatch['daily'] = true;
                        
                    }
                    else if($dateReceipt != '0') {
                        $dateReceiptTime = explode('-', $dateReceipt);
                        if(count($dateReceiptTime) == 3) {
                            $dateReceiptTime = mktime(0, 0, 0, $dateReceiptTime[1], $dateReceiptTime[2], $dateReceiptTime[0]);
                            //var_dump(date('D', $dateReceiptTime), $dateReceipt);        
                            /**** Monday ****/
                            if(date('D', $dateReceiptTime) == 'Mon') {
                               if($item->mon != '0000-00-00' && $item->mon == $dateReceipt){
                                   $isMatch['daily'] = true;
                               } 
                               else if($item->mon == '0000-00-00' && $item->mon_r == 1){
                                   $isMatch['daily'] = true;
                               }
                            }
                            
                            /**** Tuesday ****/
                            if(date('D', $dateReceiptTime) == 'Tue') {
                               if($item->tue != '0000-00-00' && $item->tue == $dateReceipt){
                                   $isMatch['daily'] = true;
                               } 
                               else if($item->tue == '0000-00-00' && $item->tue_r == 1){
                                   $isMatch['daily'] = true;
                               }
                            }
                            
                            /**** Wednesday ****/
                            if(date('D', $dateReceiptTime) == 'Wed') {
                               if($item->wed != '0000-00-00' && $item->wed == $dateReceipt){
                                   $isMatch['daily'] = true;
                               } 
                               else if($item->wed == '0000-00-00' && $item->wed_r == 1){
                                   $isMatch['daily'] = true;
                               }
                            }
                            
                            /**** Thursday ****/
                            if(date('D', $dateReceiptTime) == 'Thu') {
                               if($item->thu != '0000-00-00' && $item->thu == $dateReceipt){
                                   $isMatch['daily'] = true;
                               } 
                               else if($item->thu == '0000-00-00' && $item->thu_r == 1){
                                   $isMatch['daily'] = true;
                               }
                            }      
                            
                            /**** Friday ****/
                            if(date('D', $dateReceiptTime) == 'Fri') {
                               if($item->fri != '0000-00-00' && $item->fri == $dateReceipt){
                                   $isMatch['daily'] = true;
                               } 
                               else if($item->fri == '0000-00-00' && $item->fri_r == 1){
                                   $isMatch['daily'] = true;
                               }
                            }      
                            
                            /**** Saturday ****/
                            if(date('D', $dateReceiptTime) == 'Sat') {
                               if($item->sat != '0000-00-00' && $item->sat == $dateReceipt){
                                   $isMatch['daily'] = true;
                               } 
                               else if($item->sat == '0000-00-00' && $item->sat_r == 1){
                                   $isMatch['daily'] = true;
                               }
                            }      
                            
                            /**** Sunday ****/
                            if(date('D', $dateReceiptTime) == 'Sun') {
                               if($item->sun != '0000-00-00' && $item->sun == $dateReceipt){
                                   $isMatch['daily'] = true;
                               } 
                               else if($item->sun == '0000-00-00' && $item->sun_r == 1){
                                   $isMatch['daily'] = true;
                               }
                            }      
                        }
                    }
                }
                
                //var_dump($isMatch);
                $isPass = true;
                foreach($isMatch as $match) {
                    if($match == false){
                        $isPass = false; break;    
                    }
                }
                if($isPass == true){
                    $points[] = array('point'=>$item->point);
                }
            }   
            
            $max = 0;
            foreach($points as $item){
                if($item['point'] > $max) {
                    $max = $item['point'];
                }       
            }
            $points = array('point'=>$max);
        }
        
        $points['user_id'] = $userId;
        /*var_dump($points, $userId); 
        die*/;
        return $points;
    }
	
    
    /**
     * Get total point of each step registration 
     */
    public static function totalPointOfEachStep($step = 2) {
        $total = 0;
        if($step > 1) {
            $db = &JFactory::getDbo();
            $sql = "
                SELECT SUM(`t`.POINT) AS `totalPoint` FROM #__wrd_crpoint `t` WHERE `t`.step_no = '".$step."'
            ";
            $db->setQuery($sql);
            $total = $db->loadResult();
        }
        return $total;
    }

	public function getPageTitle(){
	
		$mydoc =& JFactory::getDocument();
		$mytitle = $mydoc->getTitle();
		return $mytitle;
	}
    
	public function getTransaction($id = 0 , $month= 0, $year = 0){
		
		$db = JFactory::getDbo();
		$query = '
		SELECT a.transaction_id,a.vip_number,a.date_receipt,a.pax,a.food,a.beverage,
		a.other,a.discount,a.netsale,a.sc,a.vat,a.total,b.name as outletname,b.code as outletcode
		FROM #__wrd_transaction as a
		INNER JOIN #__wrd_outlets as b ON a.outlet = b.code
		
		WHERE a.vip_number = '.$id.'
		';
		if(!empty($month)){
			$query .= ' and month(`date_receipt`) = '.$month ;
		}
		if(!empty($year)){
			$query .= ' and year(`date_receipt`) = '.$year ;
		}
        $query .= ' order by a.date_receipt DESC';
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		return $rs;
		
	}
    public function getUserProfilesByMemberId($mem_id = 0){
        $db = JFactory::getDBO();
        if($mem_id == 0)
            return null;           
        $db = &JFactory::getDbo();
        $query = '
            SELECT
              l_name, f_name
            FROM #__wrd_profile
            WHERE member_id = '.$mem_id;
        $db->setQuery($query);
       
		$model = $db->loadObject();
        return $model;
    }
	public function getUsernameByMemberId($mem_id = 0){
		$db = JFactory::getDBO();
		if($mem_id == 0)
			return null;          
		
        $db = &JFactory::getDbo();
		$query = 'SELECT user_id FROM #__wrd_profile WHERE member_id = '.$mem_id;
		$db->setQuery($query);
		$user = $db->loadObject();
        
		$query1 = 'SELECT name FROM #__users WHERE id = '.$user->user_id;
		$db->setQuery($query1);
		$user_name = $db->loadObject();
		
        return $user_name->name ;
	} 
    
    public function checkDuplicateUser($email){
        $db = JFactory::getDBO();
        if($email == '')
            return null;          
        
        $db = &JFactory::getDbo();
        $query = "SELECT COUNT(*) FROM #__users WHERE username = '".strval($email)."' AND block =  0";
        $db->setQuery($query);        
        $isExist = $db->loadResult();
        return $isExist;
    }      
	public function getUsernameByOutletCode($out_code = 0){
	
		if($out_code == 0)
			return null;
		$db = &JFactory::getDbo();
		$query = 'SELECT name FROM #__wrd_outlets WHERE pid != 00 and code = '.$out_code;
		$db->setQuery($query);
		$out_name = $db->loadObject();
		return $out_name->name ;
	}
	
	/*
	** Convert total from #__wrd_transaction to #__wrd_spending_summary.
	*/
	public function uSummarySpend($member_id=true,$year=true,$month=true){
		
		$db = JFactory::getDbo();
		$query = 'SELECT SUM(total) as total FROM #__wrd_transaction WHERE (vip_number = '. $member_id .') AND ( date_receipt BETWEEN  "'.$year.'-'.$month.'-01 00:00:00" AND "'.$year.'-'.$month.'-31 23:59:59")';
		$db->setQuery($query);
		$totalOfMonth = $db->loadObject();
		
		$sql = 'SELECT id,member_id,total,year,month FROM #__wrd_spending_summary WHERE (member_id ='. $member_id .') AND ((year<'.$year.') OR ((year='.$year.') AND (month <='.$month.'))) ORDER BY year DESC, month DESC LIMIT 2';
		
		$db->setQuery($sql);
		$lists = $db->loadObjectList();
		$totalFirst = 0;
		
		if(count($lists)>0){
			if($lists[0]->month == $month and $lists[0]->year == $year )
				$totalFirst = $lists[1]->total;
			else
				$totalFirst = $lists[0]->total;
		}	
		
		$diemphatsinhtrongky = $totalOfMonth->total;
		$totalEnd = $totalFirst + $diemphatsinhtrongky;
		if(count($lists) == 0){
			$query = 'INSERT INTO #__wrd_spending_summary (`member_id`, `total`, `year`, `month`) VALUES ('.$member_id.','.$diemphatsinhtrongky.','.$year.', '.$month.')';
		}
		if(count($lists) > 0){
			if(($lists[0]->year==$year)&&($lists[0]->month==$month)&&($lists[0]->member_id==$member_id)){
				$query = 'UPDATE `#__wrd_spending_summary` SET `total` = '. $totalEnd .' WHERE (`member_id`='.$member_id.') AND (year='.$year.') AND ( month='.$month.')';
			}
			else
			{
				$query = 'INSERT INTO #__wrd_spending_summary (`member_id`,`total`, `year`, `month`) VALUES ('.$member_id.','. $totalEnd .','.$year.', '.$month.')';
			}
		}
		$db->setQuery($query);
		$db->query();
	}
	
	public function updateSummaryPoint($user_id=true,$year=true,$month=true){
		
		$db = &JFactory::getDbo();
		$query = 'SELECT SUM(point) as point FROM #__wrd_point 
				WHERE (user_id = '. $user_id .') AND ( expired = 0 )
				AND ( created_date BETWEEN  "'.$year.'-'.$month.'-01 00:00:00" AND "'.$year.'-'.$month.'-31 23:59:59")';

		$life_time_query = 'SELECT SUM(point) as point FROM #__wrd_point
				WHERE (user_id = '. $user_id .') AND ( expired = 0 ) AND point > 0 
				AND ( created_date BETWEEN  "'.$year.'-'.$month.'-01 00:00:00" AND "'.$year.'-'.$month.'-31 23:59:59")';
		
		$db->setQuery($query);
		$pointOfMonth = $db->loadObjectList();
		
		$db->setQuery($life_time_query);
		$life_time_pointOfMonth = $db->loadObjectList();
		
		$sql = 'SELECT id,user_id,point,year,month,point_life_time FROM #__wrd_points_summary 
				WHERE (user_id ='. $user_id .') AND ((year<'.$year.') OR ((year='.$year.') AND (month <='.$month.'))) 
						ORDER BY year DESC, month DESC';
		$db->setQuery($sql);
		$lists = $db->loadObjectList();
		$diemdauky = 0;
		
		if(count($lists)>0){
			
			if($lists[0]->month == $month and $lists[0]->year == $year ){
				$diemdauky = $lists[1]->point;
				$point_begin_month = $lists[1]->point_life_time;
			}
			else{
				$diemdauky = $lists[0]->point;
				$point_begin_month = $lists[0]->point_life_time;
			}
		}
		
		$diemphatsinhtrongky = $pointOfMonth[0]->point;
		$diemcuoiky = $diemdauky + $diemphatsinhtrongky;
		
		$point_balance = $life_time_pointOfMonth[0]->point;
		$point_end_month = $point_begin_month + $point_balance;
		
		if(count($lists) == 0){
			$query = 'INSERT INTO #__wrd_points_summary (`user_id`,`point_life_time`, `point`, `year`, `month`) 
						VALUES ('.$user_id.','.$life_time_pointOfMonth[0]->point.','.$pointOfMonth[0]->point.','.$year.', '.$month.')';
		}
		if(count($lists) > 0){
			if(($lists[0]->year==$year)&&($lists[0]->month==$month)&&($lists[0]->user_id==$user_id)){
				$query = 'UPDATE `#__wrd_points_summary` SET `point` = '. $diemcuoiky .' , `point_life_time` = '. $point_end_month .'
						WHERE (`user_id`='.$user_id.') AND (year='.$year.') AND ( month='.$month.')';
			}
			else
			{
				$query = 'INSERT INTO #__wrd_points_summary (`user_id`,`point_life_time`, `point`, `year`, `month`) 
						VALUES ('.$user_id.','.$point_end_month.','. $diemcuoiky .','.$year.', '.$month.')';
			}
		}
		
		$db->setQuery($query);
		$db->query();
	}
	
	public static function updatePointOfUser($user_id,$member,$dob,$firstName = '',$lastName = ''){
			
		if($user_id <= 0)
			return false;

		$db = &JFactory::getDbo();
		$p_o_u = WrdHelper::getPoints($user_id);

		$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point .' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$user_id;
		$db->setQuery($sql);
		$db->query();

		//Update wrd_discount_profile
		if($member != NULL){
			
			$query = "SELECT member_id,dob,count(*) as total FROM #__wrd_discount_profile WHERE member_id=".$member;
			$db->setQuery($query);
			$rs = $db->loadObject();
			
			if($rs->total == 0){
					
					if($dob != NULL){
						$arr = explode("-",$dob);
						$dob = $arr[1]."/".$arr[2]."/".$arr[0];	
					}
					else {
						$dob = "";
					}

					$obj = new stdClass();
					$obj->f_name		=	$firstName;
					$obj->l_name		=	$lastName;
					$obj->member_id		=	$member;
					$obj->dob			=	strtotime($dob) === FALSE ? '' : $dob;
					$obj->point			=	$p_o_u->point_life_time;
					$db->insertObject('#__wrd_discount_profile', $obj);
					$full_profile = self::getUserProfile($member,'member_id');
					self::JSONPOSXMSMember("add",$full_profile);
			}
			else {
				$obj = new stdClass();
				$obj->f_name		=	$firstName;
				$obj->l_name		=	$lastName;
				$obj->member_id		=	$member;
				$obj->dob			=	strtotime($dob) === FALSE ? '' : $dob;
				$obj->point			=	$p_o_u->point_life_time;
				$db->updateObject('#__wrd_discount_profile', $obj,'member_id');
				
				$full_profile = self::getUserProfile($member,'member_id');
				self::JSONPOSXMSMember("add",$full_profile);				
			}
		}
		
		return $p_o_u->point;
	}
	
	//loadform
	public function load($data, $file = true, $reset = true)
	{
		$return = false;
	
		// Make sure we have data.
		if (!empty($data)) {
			// If the data is a file, load the XML from the file.
			if ($file) {
				// If we were not given the absolute path of a form file, attempt to find one.
				if (!is_file($data)) {
					jimport('joomla.filesystem.path');
					$data = JPath::find(self::addFormPath(), strtolower($data).'.xml');
					if (!$data) {
						return false;
					}
				}
	
				// Attempt to load the XML file.
				$xml = JFactory::getXML($data);
			}
			// Load the data as a string.
			else {
				$xml = JFactory::getXML($data, false);
			}
			// Make sure the XML was loaded.
			if ($xml) {
				// Check if any groups exist.
				if (isset($xml->fields)) {
					// Load the form groups.
					foreach ($xml->fields as $group) {
						$this->loadFieldsXML($group, $reset);
						$return = true;
					}
				}
	
				// Check if a name is set.
				if ((string)$xml->attributes()->name && $reset) {
					$this->setName((string)$xml->attributes()->name);
				}
			}
		}
	
		return $return;
	}

	
	public static function uRenewMemberId(){
		
		$db = JFactory::getDBO();
		$query_lucky = 'SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1';
		$db->setQuery($query_lucky);
		$rs_lucky = $db->loadResultArray();

		$query = 'SELECT member_id FROM #__wrd_profile';
		$query.= ' WHERE member_id NOT IN (SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1)';		
		$query.= ' ORDER BY member_id DESC LIMIT 1';
		$db->setQuery($query);
		$rs = $db->loadObject();
		$code = $rs->member_id + 1;
		
		$tmparr = $rs_lucky;
		$total = count($tmparr)*2 ;
		for($i = 0 ; $i <= $total ; $i++){
			$tmparr[] = $code + $i ;
		}
		
		$tmparr = array_unique($tmparr,SORT_NUMERIC) ;
		sort($tmparr) ;
		foreach ($tmparr as $val){
			if(in_array($val, $rs_lucky)){
				continue;
			}else{
				$code = $val;
				break;
			}
		}
		return $code;
	}
	
	function isEmail($email){
		
		return (preg_match("/[-a-zA-Z0-9_.+]+@[a-zA-Z0-9-]{2,}\.[a-zA-Z]{2,}/", $email) > 0) ? true : false;
	}
	
	function getCountryCodeFromCity($id){
		$db = &JFactory::getDbo();
		$query = 'SELECT country_id FROM #__wrd_city WHERE id = '.$id;
		return $db->setQuery($query)->loadObject()->country_id;
	}
	
	function getCityCodeFromDistric($id){
		
		$db = &JFactory::getDbo();
		$query = 'SELECT city_id FROM #__wrd_distric WHERE id = '.$id;
		return $db->setQuery($query)->loadObject()->city_id;
	}
	
	function getCountryCodeFromDistric($id){
		
		$db = &JFactory::getDbo();
		$query = 'SELECT country_id FROM #__wrd_distric WHERE id = '.$id;
		return $db->setQuery($query)->loadObject()->country_id;
	}
	
	
	public function getLpreferById($id){
		if(intval($id) == 0) return false;
		$db = &JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_lprefer WHERE id = '.$id;
		return $db->setQuery($query)->loadObject();
	}

	function getCountryById($id){
		if(intval($id) == 0 ) return false;
		$db = &JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_country WHERE id = '.$id;
		return $db->setQuery($query)->loadObject();
	}

	function getCityById($id){
		if(intval($id) == 0) return false;
		$db = &JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_city WHERE id = '.$id;
		return $db->setQuery($query)->loadObject();
	}

	function getDistricById($id){
		if(intval($id) == 0) return false;
		$db = &JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_distric WHERE id = '.$id;
		return $db->setQuery($query)->loadObject();
	}

	function getPointsofUser($id){
		
		if($id == 0)
			return 0;
		else{
			$db = JFactory::getDbo();
			$query = 'SELECT user_id,p_o_u FROM #__wrd_profile WHERE user_id='.$id;
			
			$db->setQuery($query);
			$rs = $db->loadObject();
			return intval($rs->p_o_u);
		}
	
	}
	
	function random_letters($lenght = 6){
		$mainframe = JFactory::getApplication() ;
		
		$sample = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U', 'V','W','X','Y','Z');
	    $total = count($sample);
		$vercode = '';
		
	    for ($i= 0; $i < $lenght; $i++) {
		    $rand = rand(0, $total-1) ;
		    $vercode = $vercode.$sample[$rand] ;
    	}
		
    	$vercode .= "".time() ;
    	return $vercode ;
	}
	
	function calculateExpiredDate($exp,$type = 1){
		$body['dateReceipt'] = $exp;
		//file_put_contents('point.log', $exp.PHP_EOL, FILE_APPEND);
		$db = &JFactory::getDbo();
		$query = 'SELECT value FROM #__wrd_configs WHERE seo_name = "allow_point_expire" ';
		$rs = $db->setQuery($query)->loadObject();
		
		if($rs->value == 0){
			return '0000-00-00';	
		}
		
		if($type == 1){
			$exp = strtotime($exp);
			if($exp == FALSE)
			{
				//send email report
				$body['dateReceiptConvert'] = date('Y-m-d', strtotime('first day of +13 month',$exp));;
				WrdHelper::sendEmailToAdminForDebuging($body);
				
			}
			$expireddate = date('Y-m-d', strtotime('first day of +13 month',$exp));
			//file_put_contents('point1.log', $expireddate.PHP_EOL, FILE_APPEND);
			return $expireddate;
		}
		else{
			//echo 'to be continue...';
			
			die('only support type = 1');
		}
	}
	
	public static function stringURLSafeAliasLang($string){
		$string= trim($string);
		$str = str_replace('-', '_', $string);
		$str = str_replace(' ', '_', $string);
		$str = preg_replace(array('/\s+/','/[^A-Za-z0-9\-]/'), array('-','_'), $str);
		$str = strtoupper($str);
		return $str;
	}
	
	public static function JSONPOSXMSIpConnect(){
		$arr_allow_ip = array();
		$arr_allow_ip[] = '10.1';

		$server_ip = explode('.',$_SERVER['SERVER_ADDR']);
		$str_server_ip = $server_ip[0].'.'.$server_ip[1];
		
		if(!in_array($str_server_ip,$arr_allow_ip)){
			echo 'Security Issue';
			exit();
		}
	}
	
	public static function JSONPOSXMSMember($type,$profile){
		$server_ip = '10.1.6.6';
		$port = '55759';
		
		date_default_timezone_set('Asia/Ho_Chi_Minh');
		$timezone  = +7;
		$mainframe = &JFactory::getApplication();
		
		$post = array();
		$post['Member ID'] = "8800".$profile->member_id."01";
		
		// URL of JSON Function 
		if($type == "add"){
			if($profile->gender == 'male')
				$gender = 1;
			else 
				$gender = 0;
			
			
			$post['Date of Birth'] = strval(date("m/d/Y",strtotime($profile->dob))); 			//$dob;
			$post['Member Since'] = strval(date("m/d/Y",strtotime($profile->created_date)));	// '2/28/2013';
			$post['First Name'] = strval($profile->f_name) ;									//'DinhDinhDinh';
			$post['Last Name'] = strval($profile->l_name);										// 'ChauChauChauChau';
			$post['Name on Card'] = strval($profile->name_on_card);								//'Chau Tran Hoang Dinhhhhh';
			$post['Sex'] = $gender; 															//'1';
			$post['Lifetime Point'] = strval($profile->point_life_time); 						//'1000000'; 
			$post['Balance Point'] = strval($profile->p_o_u); 									//'100000';
			$post['Last Modified'] = strval(date("m/d/Y",strtotime($profile->modify_date))); 	//'2/15/2013';
			$target_url = $server_ip.':'.$port.'/MemberService.svc/addMember';
		}
		else if($type == "update"){
			//Goi ham update
			$target_url = $server_ip.':'.$port.'/MemberService.svc/editMember';
		}
		else if($type == "delete"){
			//Goi ham update
			$target_url = $server_ip.':'.$port.'/MemberService.svc/delMember';
		}

		// Encode $POST into JSON Type
		$json = str_replace('\/','/',json_encode($post));
		
		// Send JSON files
		$result = self::JSONSEND($target_url,$json);
		
		// Try send JSON file again in case NETWORK failure 
		$path = JPATH_SITE.'/logs-wrd/';
		$msg = '';
		if($result == ''){
			
			for($i = 0;$i<=3;$i++){
			
				$result = self::JSONSEND($target_url,$json);
				
				if($result == '\"success\"'){
					
					if($type == "add"){
						
						file_put_contents($path."members/add-success/".date("Y-m-d").'-add-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
					}
					else if($type == "update"){
						
						file_put_contents($path."members/update-success/".date("Y-m-d").'-update-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n", FILE_APPEND | LOCK_EX);		
					}
					else if($type == "delete"){
						
						file_put_contents($path."members/delete-success/".date("Y-m-d").'-delete-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n", FILE_APPEND | LOCK_EX);		
					}
					$msg = 'success';
					break;
					
				}
				else if($result == '') {
					
					if($i == 3){
						
						if($type == "add"){
							file_put_contents($path."members/add-failure/".date("Y-m-d").'-add-failure.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
						}
						else if($type == "update"){
							file_put_contents($path."members/update-failure/".date("Y-m-d").'-update-failure.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n", FILE_APPEND | LOCK_EX);	
						}
						else if($type == "delete"){
							file_put_contents($path."members/delete-failure/".date("Y-m-d").'-delete-failure.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n", FILE_APPEND | LOCK_EX);	
						}
					}
					$msg = 'fail';
					continue;
				}
			}
			
			
		}
		else if($result == '\"success\"'){
			
			if($type == "add"){
				
				file_put_contents($path."members/add-success/".date("Y-m-d").'-add-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}
			else if($type == "update"){
				
				file_put_contents($path."members/update-success/".date("Y-m-d").'-update-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n", FILE_APPEND | LOCK_EX);
			}
			else if($type == "delete"){
				
				file_put_contents($path."members/delete-success/".date("Y-m-d").'-delete-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n", FILE_APPEND | LOCK_EX);
			}
			
			$msg = 'success';
		}
		
		return $msg;
		
	}
	
	public static function JSONSEND($target_url,$json){
		//exec ('D:\\Program Files\\Fiddler2\\Fiddler.exe');
		$server_ip = '10.1.6.6';
		$port = '55759';
		// Set up CURL to send JSON files
		$headers = array(
			'User-Agent: Fiddler',
			'Host:'.$server_ip.':'.$port,
			//'Content-Type: application/json; charset=utf-8'
			'Content-Type: application/x-www-form-urlencoded'
		);
		
	    $ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
		curl_setopt($ch, CURLOPT_URL,$target_url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 120);
		curl_setopt($ch, CURLOPT_POST,1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' );

		// Send JSON files
		$result = curl_exec($ch);
		
		curl_close($ch);
		return $result;
	}
	
	public static function getPublishRule(){
	
		$db = &JFactory::getDbo();
		$query = "SELECT * FROM `#__wrd_discount` where published = 1 AND
				( published_up = '0000-00-00'
				OR published_down = '0000-00-00'
				OR (published_up <= '".date("Y-m-d")."' AND published_down >= '".date("Y-m-d")."')) ORDER BY priority DESC, id DESC";
		
		$db->setQuery($query);
		return $db->loadObjectList();
	}
	
	public static function orderList($list){
		$tmp_arr = array();
		foreach ($list as $row){
			$list_outlet = unserialize($row->o_code);
			foreach ($list_outlet as $outlet)
				$tmp_arr[$outlet][$row->priority][$row->id] = $row;
		}
		
		return $tmp_arr;
	}
	
	
	public static function JSONPOSXMSIsValidMemberID($member_id){
		$str_len = strlen($member_id);
		$arr = array();
		
		if($str_len == 5){
			$member_id = '1'.$member_id;
			$arr['long'] = '8800'.$member_id.'01';
			$arr['short'] = $member_id;
			
			return $arr;
		}
		if($str_len == 6){
			$arr['long'] = '8800'.$member_id.'01';
			$arr['short'] = $member_id;
			
			return $arr;
		}
		elseif($str_len == 12){
			$subfix_id = substr($member_id,-2);
			$prefix_id = substr($member_id,0,4);
			
			if($subfix_id != '01' || $prefix_id != '8800')
				return false;
			else{
				$arr['long'] = $member_id;
				$arr['short'] = substr($member_id, 4, -2);
				
				return $arr;
			}
		}
		else
			return false;
	}
	
	public static function getProfileDiscountPolicy($member_id){
		
		$db = &JFactory::getDbo();
		$query = 'SELECT * FROM `#__wrd_discount_profile` where member_id = '.$member_id;
		$profile = $db->setQuery($query)->loadObject();
		
		$cdate = date('j');
		$cmonth = date ('n');
		
		$dbstr = explode('-', $profile->dob);
		$db_date = intval($dbstr[2]);
		$db_month = intval($dbstr[1]);
		
		if($cdate == $db_date && $cmonth == $db_month)
			$profile->in_dob = 1;
		else
			$profile->in_dob = 0;
		
		if($cmonth == $db_month) $profile->in_month_dob = 1;
		else $profile->in_month_dob = 0;
		
		return $profile;
	}
	
	public static function getTransactionDiscountPolicy($outlet){
		
		$db = &JFactory::getDbo();
		$query = 'SELECT * FROM `#__wrd_discount_transaction` 
					WHERE outlet_id = '.$outlet.' AND `date` = "'.date("Y-m-d").'"';
		
		return $db->setQuery($query)->loadObject();
	}
	
	public static function checkRuleMatch($rule_id,$profile,$transaction,$outlet_code,$check = 0){
		$rs = false;
		switch ($rule_id->rule) {
			case '1':
				$rs = WrdHelper::checkRule1($rule_id,$profile,$check);
				break;
			case '1a':
				$rs = WrdHelper::checkRule1a($rule_id,$profile,$check);
				break;
			case '2':
				$rs = WrdHelper::checkRule2($rule_id,$profile,$check);
				break;
			case '3':
				$rs = WrdHelper::checkRule3($rule_id,$transaction,$check);
				break;
			case '4':
				$rs = WrdHelper::checkRule4($rule_id,$profile,$outlet_code,$check);
				break;
			case '5':
				$rs = WrdHelper::checkRule5($rule_id,$profile,$outlet_code,$check);
				break;
			case '6':
				$rs = WrdHelper::checkRule6($rule_id,$profile,$outlet_code,$check);
				break;
		}
		
		return $rs;
	}

	//Apply % or VND discount when VIPCard holders swipe their card on their birthday
	function checkRule1($rule_id,$profile,$check){
		//print_r($profile);
		$arr = array();
		$arr['msg'] = $rule_id->message;
		$arr['rule'] = $rule_id->rule;
		
		$current_year = date('Y'); 
		
		if($profile->in_dob == 1 ){
			if($rule_id->percent == 0)
				$arr['discount'] = $rule_id->cash;
			else
				$arr['discount'] = $rule_id->percent.'%';
			
			
			if($check == 0){
				$db = JFactory::getDbo();
				$query = 'UPDATE #__wrd_discount_profile SET birthday_year ="'.$current_year.'" WHERE member_id = '.$profile->member_id;
				$db->setQuery($query);
				$db->query();
			}
			
			return $arr;
		}
		else
			return false;
	}
	
	//Apply % or VND discount when VIPCard holders swipe their card on their birthday month
	function checkRule1a($rule_id,$profile,$check){
		//print_r($profile);
		$arr = array();
		$arr['msg'] = $rule_id->message;
		$arr['rule'] = $rule_id->rule;
		
		$current_year = date('Y'); 
		
		if($profile->in_month_dob == 1){
			if($rule_id->percent == 0)
				$arr['discount'] = $rule_id->cash;
			else
				$arr['discount'] = $rule_id->percent.'%';

			return $arr;
		}
		else
			return false;
	}
	
	//Apply % or VND discount when VIPCard holders swipe their card on 1st time of using
	function checkRule2($rule_id,$profile,$check){
		$arr = array();
		$arr['msg'] = $rule_id->message;
		$arr['rule'] = $rule_id->rule;
		
		//print_r($profile);
		if($profile->first_use == 0){
			if($rule_id->percent == 0)
				$arr['discount'] = $rule_id->cash;
			else
				$arr['discount'] = $rule_id->percent.'%';
			
			if($check == 0){
				$db = JFactory::getDbo();
				$query = 'UPDATE #__wrd_discount_profile SET first_use ="1" WHERE member_id = '.$profile->member_id;
				
				$db->setQuery($query);
				$db->query();
			}
			
			return $arr;
		}
		else
			return false;
	}
	
	//Apply % or VND discount when VIPCard holder is the 100th VIP member who uses the card at the restaurant outlet that day
	function checkRule3($rule_id,$transaction,$check){
		$arr = array();
		$arr['msg'] = $rule_id->message;
		$arr['rule'] = $rule_id->rule;
		
		if($transaction->used == 0){
			
			if((intval($transaction->total) + 1) == intval($rule_id->ordinary)){
				$db = &JFactory::getDbo();
				
				if($check == 0){
					$query = 'UPDATE #__wrd_discount_transaction SET `used` = 1 
							WHERE outlet_id = '.$transaction->outlet_id.' AND `date` = "'.date("Y-m-d").'"';

					$db->setQuery($query)->query();
				}
				
				if($rule_id->percent == 0)
					$arr['discount'] = $rule_id->cash;
				else
					$arr['discount'] = $rule_id->percent.'%';

				return $arr;
			}
			else
				return false;
		}
		else
			return false;
	}
	
	//Apply % or VND discount when VIPCard holder points reach 10,000 points or 20,000 points or 30,000 points etc…
	function checkRule4($rule_id,$profile,$outlet_code,$check){
	
		$arr = array();
		$arr['msg'] = $rule_id->message;
		$arr['rule'] = $rule_id->rule;
		
		$floor_point_arr = unserialize($profile->floor_point);
		$floor_point = $floor_point_arr[$rule_id->id][$rule_id->multiples];
		$tmp_mul = floor(intval($profile->point) / intval($rule_id->multiples));
		
		if($tmp_mul > $floor_point_arr[$rule_id->id][$rule_id->multiples]){
				
			if($check == 0){
				$floor_point_arr[$rule_id->id][$rule_id->multiples] = $tmp_mul;
				$update_obj = new stdClass();
				$update_obj->member_id = $profile->member_id;
				$update_obj->floor_point = serialize($floor_point_arr);
			
				$db = JFactory::getDbo();
				$db->updateObject('#__wrd_discount_profile', $update_obj, 'member_id');
			}
		
			if($rule_id->percent == 0)
				$arr['discount'] = $rule_id->cash;
			else
				$arr['discount'] = $rule_id->percent.'%';
			
			return $arr;
		}
		else
			return false;
	}
	
	//Apply % or VND discount when VIPCard holder card number matches with the lucky draw number that day
	function checkRule5($rule_id,$profile,$outlet_code,$check){
		$arr = array();
		$arr['msg'] = $rule_id->message;
		$arr['rule'] = $rule_id->rule;
		$is_inarray = false;
				
		$available_lucky = unserialize($profile->available_lucky);
		$list_array_num = array(substr($profile->member_id, -6),substr($profile->member_id, -5),substr($profile->member_id, -4),substr($profile->member_id, -3),substr($profile->member_id, -2),substr($profile->member_id, -1));

		if($rule_id->lucky != ''){
			$lucky_arr = unserialize($rule_id->lucky);
			
			foreach($list_array_num as $number_item){
				if(in_array($number_item, $lucky_arr)){
					$is_inarray = true;
					break;
				}
			}

			if($is_inarray === true){
				if(intval($available_lucky[$rule_id->id]) == 0){

					if($check == 0){
						$available_lucky[$rule_id->id] = $outlet_code;
						$update_obj = new stdClass();
						$update_obj->member_id = $profile->member_id;
						$update_obj->available_lucky = serialize($available_lucky);

						$db = JFactory::getDbo();
						$db->updateObject('#__wrd_discount_profile', $update_obj, 'member_id');
					}
					
					if($rule_id->percent == 0)
						$arr['discount'] = $rule_id->cash;
					else
						$arr['discount'] = $rule_id->percent.'%';
					
					return $arr;
				}else{
					return false;
				}
			}
		}
		else{
			return false;
		}
	}

	function  checkRule6($rule_id,$profile,$outlet_code,$check){
		$arr = array();
		$arr['msg'] = $rule_id->message;
		$arr['rule'] = $rule_id->rule;
		
		if($rule_id->percent == 0)
			$arr['discount'] = $rule_id->cash;
		else
			$arr['discount'] = $rule_id->percent.'%';
		
		return $arr;
	}
	
	
	public static function uSpend($post){
		$post = (array)$post;
		$year = 2013;$month = 01;
	
		if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
			while(($month != date('m'))||($year != date('Y'))){
				WrdHelper::uSummarySpend($post['member_id'],$year,$month);
				if($month+1 <=12) ++$month;
				else {$month = 1;++$year;}
			}
		}
	
		WrdHelper::uSummarySpend($post['member_id'],date('Y'),date('m'));
		$db = JFactory::getDbo();
		$sql = 'SELECT total,member_id FROM #__wrd_spending_summary WHERE member_id = '. $post['member_id'] .' ORDER BY year DESC,month DESC LIMIT 1';
		$db->setQuery($sql);
		$rs = $db->loadObject();
		$query = 'UPDATE #__wrd_profile SET total_spend = '.$rs->total.' WHERE member_id = '.$post['member_id'];
		$db->setQuery($query);
		$db->query();
		$dob = $post['year_birth']."-".$post['month_birth']."-".$post['day_birth'];
		WrdHelper::updatePointOfUser($post['user_id'],$post['member_id'],$dob,$post['f_name'],$post['l_name']);
		return true;
	}
	
	public static function uPoint($post){
		$post = (array)$post;
		WrdHelper::convertTransactionToPoint($post['member_id']);
		$year = 2013;$month = 01;
		if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
			while(($month != date('m'))||($year != date('Y'))){
				WrdHelper::updateSummaryPoint($post['user_id'],$year,$month);
				if($month+1 <=12) ++$month;
				else {$month = 1;++$year;}
			}
		}
	
		WrdHelper::updateSummaryPoint($post['user_id'],date('Y'),date('m'));
		$db = JFactory::getDbo();
		$p_o_u = WrdHelper::getPoints($post['user_id']);
		$sql = 'UPDATE #__wrd_profile SET p_o_u = '.intval($p_o_u->point) .' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$post['user_id'];
		$db->setQuery($sql);
		$db->query();
		$dob = $post['year_birth']."-".$post['month_birth']."-".$post['day_birth'];
		WrdHelper::updatePointOfUser($post['user_id'],$post['member_id'],$dob,$post['f_name'],$post['l_name']);
		return true;
	}
	
	function convertTransactionToPoint($vipnumber){
		$db = JFactory::getDbo();
		$user = JFactory::getUser();
		$created_id = 42;
	
		$sql = "DELETE FROM #__wrd_point WHERE (user_id = 0) OR (user_id = NULL)";
		$db->setQuery($sql);
		$db->query();
		$query = "SELECT id,food,beverage,other,netsale,discount,date_receipt FROM #__wrd_transaction WHERE `vip_number` = ".$vipnumber;
		$db->setQuery($query);
		$data = $db->loadObjectList();
	
		if(count($data) > 0){
			$moneyForOnePoint = PointProvider::getConfigByName($db, 'money_for_one_point');
			$moneyForOnePoint = ($moneyForOnePoint > 0 ? $moneyForOnePoint : 50000);
			$defaultPointPerMoney  = PointProvider::getConfigByName($db, 'default_point_per_money');
			$defaultPointPerMoney = ($defaultPointPerMoney > 0 ? $defaultPointPerMoney : 100);
			foreach($data as $val=>$item){
				//Call function machPoint in components/com_wrd/helpers/wrd.php.Note by Hung
				$point = WrdHelper::machPoint($item->id,'transaction');
				if($point->point == 0){
					$point->point = $defaultPointPerMoney;
				}
	
				if(($point->f==0)&&($point->b==0)&&($point->o==1))
					$p = intval(($item->other) / $moneyForOnePoint) * $point->point;
				else if(($point->f==0)&&($point->b==1)&&($point->o==0))
					$p = intval(($item->beverage) / $moneyForOnePoint) * $point->point;
				else if(($point->f==0)&&($point->b==1)&&($point->o==1))
					$p = intval(($item->beverage+$item->other) / $moneyForOnePoint) * $point->point;
				else if(($point->f==1)&&($point->b==0)&&($point->o==0))
					$p = intval($item->food / $moneyForOnePoint) * $point->point;
				else if(($point->f==1)&&($point->b==0)&&($point->o==1))
					$p = intval(($item->food+$item->other) / $moneyForOnePoint) * $point->point;
				else if(($point->f==1)&&($point->b==1)&&($point->o==0))
					$p = intval(($item->food+$item->beverage) / $moneyForOnePoint) * $point->point;
				else
					$p = intval(($item->netsale) / $moneyForOnePoint) * $point->point;
				$query = "SELECT count(id) as total FROM #__wrd_point WHERE user_id = ".$point->user_id ." AND `transaction` = ".$point->tran;
				$db->setQuery($query);
				$rs = $db->loadObject();
	
				if($rs->total==0):
				$expire  = WrdHelper::calculateExpiredDate($item->date_receipt);
				$obj = new stdClass;
				$obj->id = null;
				$obj->user_id = $point->user_id;
				$obj->transaction = $point->tran;
				$obj->type = 'transaction';
				$obj->point = $p ;
				$obj->expire = $expire;
				$obj->point = $p ;
				$obj->des = 'transaction';
				$obj->created_id = $created_id ;
	
				//$obj->created_date = date('Y-m-d') ;
				$obj->created_date = $item->date_receipt;
				$obj->modify_id = '' ;
				$obj->modify_date = '' ;
				$db->insertObject('#__wrd_point', $obj);
	
				// Update lai point summary cho user
				$month = date('m',strtotime($obj->created_date));
				$year = date('Y',strtotime($obj->created_date));
	
				if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
	
					while(($month != date('m'))||($year != date('Y'))){
						WrdHelper::updateSummaryPoint($obj->user_id,$year,$month);
						if($month+1 <=12) ++$month;
						else {$month = 1;++$year;}
					}
	
					WrdHelper::updateSummaryPoint($obj->user_id,date('Y'),date('m'));
				}
				endif;
			}
		}
	
		return true;
	}
	
	public static function checkMerged($member_id){
		$db = &JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_mergeid WHERE member_id = '.$member_id;

		$rs = $db->setQuery($query)->loadObject();
		if($rs->merge_member_id == '')
			return false;
		else
			return $rs;
	}
	
	public static function sendEmailToAdminForDebuging($emailBody)
	{
		$toEmail[] = 'nhan.nguyen@wmcvietnam.com';
		$mailFrom = 'WMC VIP';
		$emailSubject = 'Debugging';
		$emailBody = json_encode($emailBody);
		return JUtility::sendMail($mailFrom, 'WMCVIP', $toEmail, $emailSubject, $emailBody,1);
	}
	
	function getTextBetweenTags($string, $tagname) {
		$pattern = "/{$tagname}(.*){\/$tagname}/";
		preg_match($pattern, $string, $matches);
		return $matches[1];
	}
}
?>